AcWing 1113. 红与黑 JAVA
原题链接
简单
作者:
天乔巴夏丶
,
2021-01-14 00:30:10
,
所有人可见
,
阅读 391
import java.io.*;
public class Main {
static int n = 25, row, col,cnt;
static int[] dx = {-1, 0, 1, 0}, dy = {0, 1, 0, -1};
static char[][] g = new char[n][n];
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true) { // 多组测试用例
cnt = 0; // 每个用例都初始化一下 0
String[] ss = reader.readLine().split(" ");
row = Integer.parseInt(ss[1]);
col = Integer.parseInt(ss[0]);
// 读到0 0 结束
if (row == 0 || col == 0) break;
int x = 0, y = 0;
for (int i = 0; i < row; i++) {
String s = reader.readLine();
for (int j = 0; j < col; j++) {
g[i][j] = s.charAt(j);
if (g[i][j] == '@') { // 记录一下初始化的x y的位置
x = i;
y = j;
}
}
}
dfs(x, y); // 开始dfs
System.out.println(cnt);
}
}
static void dfs(int x, int y) {
g[x][y] = '#'; // 标记一下 走过了
cnt++;
for (int i = 0; i < 4; i++) {
int a = x + dx[i];
int b = y + dy[i];
// 不越界 且 为黑 才继续走
if (a >= 0 && a < row && b >= 0 && b < col && g[a][b] == '.') {
dfs(a, b);
}
}
}
}