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.
Example 1:
Input: 11110 11010 11000 00000 Output: 1
Example 2:
Input: 11000 11000 00100 00011 Output: 3
这道求岛屿数量的题的本质是求矩阵中连续区域的个数,很容易想到需要用深度优先搜索DFS来解,我们需要建立一个visited数组用来记录某个位置是否被访问过,对于一个为‘1’且未被访问过的位置,我们递归进入其上下左右位置上为‘1’的数,将其visited对应值赋为true,继续进入其所有相连的邻位置,这样可以将这个连通区域所有的数找出来,并将其对应的visited中的值赋true,找完次区域后,我们将结果res自增1,然后我们在继续找下一个为‘1’且未被访问过的位置,以此类推直至遍历完整个原数组即可得到最终结果
class Solution {
public int numIslands(char[][] grid) {
if (grid.length == 0 || grid[0].length == 0) {
return 0;
}
int res = 0;
int m = grid.length;
int n = grid[0].length;
boolean[][] visit = new boolean[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == '1' && !visit[i][j]) {
dfs(grid, visit, i, j);
res++;
}
}
}
return res;
}
private void dfs(char[][] grid, boolean[][] visit, int x, int y) {
if (x < 0 || x >= grid.length) {
return;
}
if (y < 0 || y >= grid[0].length) {
return;
}
if (grid[x][y] != '1' || visit[x][y]) {
return;
}
visit[x][y] = true;
dfs(grid, visit, x + 1, y);
dfs(grid, visit, x - 1, y);
dfs(grid, visit, x, y + 1);
dfs(grid, visit, x, y - 1);
}
}