红与黑【DFS之联通性模型】
这里附带打个广告——————我做的所有的题解
包括基础提高以及一些零散刷的各种各样的题
思路
深度优先遍历————>不开st数组就每次把遍历过的点变成条件不让遍历的点的类型即可。起点预处理一下也算黑色瓷砖。
java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
static int N = 25, n, m, x, y, cnt;
static char[][] g = new char[N][N];
static int[] dx = {-1, 0, 1, 0}, dy = {0, 1, 0, -1};
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static void dfs(int x, int y) {
if (g[x][y] == '#') return;
if (g[x][y] == '.') {
g[x][y] = '#';
cnt ++;
}
for (int i = 0; i < 4; i++) {
int a = x + dx[i], b = y + dy[i];
if (a < 0 || a >= n || b < 0 || b >= m) continue;
if (g[a][b] == '#') continue;
dfs(a, b);
}
}
public static void main(String[] args) throws IOException {
while (true) {
String[] s1 = br.readLine().split(" ");
m = Integer.parseInt(s1[0]);
n = Integer.parseInt(s1[1]);
if (n == 0 && m == 0) break;
cnt = 0;
for (int i = 0; i < n; i++) {
String s2 = br.readLine();
for (int j = 0; j < m; j++) {
g[i][j] = s2.charAt(j);
if (g[i][j] == '@') {
x = i;
y = j;
g[i][j] = '.';
}
}
}
dfs(x, y);
System.out.println(cnt);
}
}
}