新知,扫描整个grid,将1的周围都设为0(dfs),这样有几个1,就有几个岛
至于用union-find的解法,之后研习
好了,可以先去吃午饭了
public class Solution {
public int numIslands(char[][] grid) {
int num = 0;
if (grid == null || grid.length == 0 || grid[0] == null || grid[0].length == 0) {
return 0;
}
for (int x = 0; x < grid.length; x++) {
for (int y = 0; y < grid[0].length; y++) {
if (grid[x][y] == '1') {
num++;
numIslandsHelper(x, y, grid);
}
}
}
return num;
}
private void numIslandsHelper(int x, int y, char[][] grid) {
grid[x][y] = '0';
if (x - 1 >= 0 && grid[x - 1][y] == '1') {
numIslandsHelper(x - 1, y, grid);
}
if (y - 1 >= 0 && grid[x][y - 1] == '1') {
numIslandsHelper(x, y - 1, grid);
}
if (x + 1 < grid.length && grid[x + 1][y] == '1') {
numIslandsHelper(x + 1, y, grid);
}
if (y + 1 < grid[0].length && grid[x][y + 1] == '1') {
numIslandsHelper(x, y + 1, grid);
}
}
}
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:
11110
11010
11000
00000
Answer: 1
Example 2:
11000
11000
00100
00011
Answer: 3

本文介绍了一种使用深度优先搜索(DFS)算法解决岛屿数量计算问题的方法。通过遍历二维网格地图,将每个‘1’(陆地)标记为‘0’(水域),以此消除相连的陆地并计算岛屿总数。
525

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



