Number of Islands
Given an m x n
2D binary grid grid
which represents a map of '1'
s (land) and '0'
s (water), return 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.
Example 1:
Input: grid = [ ["1","1","1","1","0"], ["1","1","0","1","0"], ["1","1","0","0","0"], ["0","0","0","0","0"] ] Output: 1
Example 2:
Input: grid = [ ["1","1","0","0","0"], ["1","1","0","0","0"], ["0","0","1","0","0"], ["0","0","0","1","1"] ] Output: 3
class Solution {
public int numIslands(char[][] grid) {
//广度优先遍历
//如果队首节点未越界且等于1,将其上下左右节点全添加进队列
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);
count++;
}
}
}
return count;
}
public void bfs(char[][] grid, int i, int j) {
Queue<int[]> qq = new LinkedList();//队列里存的是下标
qq.add(new int[] {i, j});
while (!qq.isEmpty()) {
int[] cur = qq.remove();
i = cur[0];
j = cur[1];
if (i >= 0 && i < grid.length && j >= 0 && j < grid[0].length && grid[i][j] == '1') {
grid[i][j] = 0;
qq.add(new int[] {i + 1, j});
qq.add(new int[] {i - 1, j});
qq.add(new int[] {i, j + 1});
qq.add(new int[] {i, j - 1});
}
}
}
}