简单的dfs问题,适合dfs入门,另外这题也有点像uva10006,附上AC代码。
代码:
import java.util.Scanner;
public class Main {
static char[][] pic;
static int cnt;
static int v;
static int h;
static int[] dir1 ={-1,0,0,1};
static int[] dir2 ={0,-1,1,0};
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while(true){
h = in.nextInt();
v = in.nextInt();
if(v == 0) break;
in.nextLine();
pic = new char[v][h];
int sx=0, sy=0;
for(int i = 0; i<v; i++){
String string = in.nextLine();
if(string.contains("@")){
sx = i;
while(string.charAt(sy) != '@') sy++;
}
pic[i] = string.toCharArray();
}
cnt=0;
dfs(sx,sy);
System.out.println(cnt);
}
}
private static void dfs(int sx, int sy) {
pic[sx][sy] = 'X';
cnt++;
for(int j = 0; j<=3; j++){
int dx = sx+dir1[j];
int dy = sy+dir2[j];
if(dx>=0 && dx<v && dy>=0 && dy<h && pic[dx][dy]=='.' )
dfs(dx, dy);
}
}
}