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
把1看作小岛,0看作水,而且数组的外围默认是水。
上下左右算连通,斜方向不算。
问小岛有多少个
思路:
DFS
本质上是求1的连通区域,
因此每走到一个1处,搜索它上下左右是否为1,是1就算同一片区域,同时搜索完后将这个位置的1改为0,防止重复搜索。
如果不想修改原数组,可用和grid同样大小的boolean数组表示每个位置是否已经被访问过。
public int numIslands(char[][] grid) {
int num = 0;
int rows = grid.length;
int cols = grid[0].length;
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
num += grid[i][j] - '0';
dfs(grid, i, j, rows, cols);
}
}
//System.out.println(grid[0][0]);
return num;
}
public void dfs(char[][] grid, int i, int j, int rows, int cols) {
if (i < 0 || i >= rows || j < 0 || j >= cols || grid[i][j] == '0') {
return;
}
grid[i][j] = '0';
dfs(grid, i-1, j, rows, cols); //up
dfs(grid, i+1, j, rows, cols); //down
dfs(grid, i, j-1, rows, cols); //left
dfs(grid, i, j+1, rows, cols); //right
}
注释的地方为表示访问过的visited数组
class Solution {
//boolean[][] visited;
int m;
int n;
public int numIslands(char[][] grid) {
int num = 0;
m = grid.length;
n = grid[0].length;
//visited = new boolean[m][n];
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(grid[i][j] == '0') continue;
dfs(grid, i, j);
num ++;
}
}
return num;
}
void dfs(char[][] grid, int i, int j) {
if(i < 0 || i >=m || j < 0 || j >=n) return;
if(grid[i][j] == '0') return;
grid[i][j] = '0';
//visited[i][j] = true;
dfs(grid, i-1, j);
dfs(grid, i, j-1);
dfs(grid, i, j+1);
dfs(grid, i+1, j);
}
}
本文介绍了一种使用深度优先搜索(DFS)算法计算二维网格中岛屿数量的方法。算法通过遍历每个单元格,当遇到陆地('1')时,进行DFS搜索,标记已访问并递归搜索相邻的陆地,避免重复计数,最终返回岛屿总数。
653

被折叠的 条评论
为什么被折叠?



