【JAVA】PKU ACM 1979
时间:2010-10-12 来源:老马睡不醒
爽,一次AC。。。
========================================
import java.util.*;
/* '.' 黑砖
* '#' 红砖
* '@' 起始位置
* '-' 已经经过
* room[h][w]
* 从左到右为w
* 从上到下为h
*/
class Count {
public int n = 0;
}
public class Main {
public static void recursion(char[][] room, int h, int w, Count c) {
for (int i = 0; i < 4; i++) {
switch (i) {
case 0: //上
h--;
if (h >= 0 && room[h][w] == '.') {
room[h][w] = '-';
c.n++;
recursion(room, h, w, c);
}
h++;
break;
case 1: //下
h++;
if (h < room.length && room[h][w] == '.') {
room[h][w] = '-';
c.n++;
recursion(room, h, w, c);
}
h--;
break;
case 2: //左
w--;
if (w >= 0 && room[h][w] == '.') {
room[h][w] = '-';
c.n++;
recursion(room, h, w, c);
}
w++;
break;
case 3: //右
w++;
if (w < room[0].length && room[h][w] == '.') {
room[h][w] = '-';
c.n++;
recursion(room, h, w, c);
}
w--;
break;
}
}
}
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
int w, h, wl, hl;
w = h = wl = hl = 0;
while ((wl = cin.nextInt()) != 0 &&
(hl = cin.nextInt()) != 0) {
//输入
char[][] room = new char[hl][wl];
for (int i = 0; i < hl; i++) {
String s = cin.next();
for (int j = 0; j < wl; j++) {
room[i][j] = s.charAt(j);
if (room[i][j] == '@') {
h = i;
w = j;
}
}
}
//递归遍历
Count c = new Count();
room[h][w] = '-';
c.n++;
recursion(room, h, w, c);
//打印结果
System.out.println(c.n);
}
}
}
相关阅读 更多 +










