🍑 算法题解专栏
输入
6 9
....#.
.....#
......
......
......
......
......
#@...#
.#..#.
0 0
输出
45
import java.util.*;
class Main
{
static int N = 30,n,m;
static char[][] g = new char[N][N];
static boolean[][] st = new boolean[N][N];
static int[] dx = {-1,1,0,0};
static int[] dy = {0,0,-1,1};
static int dfs(int x,int y)
{
int cnt = 1;//当前点也算一个
st[x][y] = true;
for(int i = 0; i < 4; i++)
{
int xx = x + dx[i];
int yy = y + dy[i];
if(xx < 0 || xx >= n || yy < 0 || yy >= m )
continue;
if(st[xx][yy] || g[xx][yy] == '#') continue;
cnt += dfs(xx,yy);
}
return cnt;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
while(sc.hasNext())
{
//注意 行数和列数 的输入顺序
m = sc.nextInt();
n = sc.nextInt();
if(n == 0 && m == 0)
break;
for(int i = 0; i < n; i++)
{
String s = sc.next();
for(int j = 0; j < m; j++)
g[i][j] = s.charAt(j);
}
int x = 0;
int y = 0;
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
{
if(g[i][j] == '@')
{
x = i;
y = j;
}
st[i][j] = false;
}
System.out.println(dfs(x,y));
}
}
}