1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
import java.util.LinkedList;
import java.util.Queue;
public class IslandCounter {
public int numIslands(char[][] grid) {
if (grid == null || grid.length == 0) return 0;
int count = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == '1') {
bfs(grid, i, j); // 进行BFS
count++;
}
}
}
return count;
}
private void bfs(char[][] grid, int x, int y) {
Queue<int[]> queue = new LinkedList<>();
queue.offer(new int[]{x, y});
grid[x][y] = '0'; // 标记为已访问
int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; // 四个方向
while (!queue.isEmpty()) {
int[] cur = queue.poll();
for (int[] dir : directions) {
int nextx = cur[0] + dir[0];
int nexty = cur[1] + dir[1];
// 检查边界和水域
if (nextx >= 0 && nextx < grid.length && nexty >= 0 && nexty < grid[0].length && grid[nextx][nexty] == '1') {
queue.offer(new int[]{nextx, nexty}); // 加入队列
grid[nextx][nexty] = '0'; // 标记为已访问
}
}
}
}
}
|