Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
思路:碰見是1的點就進行寬度搜索,并把它的所有鄰島標記為0,總島數+1.
public int numIslands(char[][] grid) {
if (grid == null || grid.length == 0 || grid[0].length == 0) {
return 0;
}
int res = 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);
res++;
}
}
}
return res;
}
private void bfs(char[][] grid, int i, int j) {
int[] dx = {0, 1, 0, -1};
int[] dy = {1, 0, -1, 0};
Queue<int[]> q = new LinkedList<>();
int[] coor = {i, j};
q.offer(coor);
while (!q.isEmpty()) {
int[] cur = q.poll();
grid[cur[0]][cur[1]] = '0';
for (int k = 0; k < 4; k++) {
int tx = cur[0] + dx[k];
int ty = cur[1] + dy[k];
if (tx < 0 || tx >= grid.length || ty < 0 || ty >= grid[0].length || grid[tx][ty] == '0') {
continue;
}
int[] neighbor = {tx, ty};
q.offer(neighbor);
}
}
}