public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int m = scanner.nextInt();
int n = scanner.nextInt();
int nums[][] = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
nums[i][j] = scanner.nextInt();
}
}
scanner.close();
int count = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (nums[i][j] >= 1) { // 非0元素的连续区域
if (route(m, n, i, j, nums) >= 1) {
count++;
}
}
}
}
System.out.println(count);
}
/**
* dfs
*
* @param i
* @param j
* @param x
* @param y
* @return
*/
private static int route(int i, int j, int x, int y, int nums[][]) {
if (x < 0 || x >= i || y <= 0 || y >= j || nums[x][y] == 0) { // 不符合条件
return 0;
}
nums[x][y] = 0; // 当前位置置为0,放置再次扫描
// +1表示当前元素
return route(i, j, x - 1, y, nums) + route(i, j, x + 1, y, nums) + route(i, j, x, y - 1, nums) + route(i, j, x, y + 1, nums) + 1;
}
}
dfs解决区域连续问题
最新推荐文章于 2024-09-10 10:21:38 发布