https://leetcode.com/problems/number-of-islands/
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
方法一:并查集。
public class Solution {
public int numIslands(char[][] grid) {
if (grid == null || grid.length == 0 || grid[0].length == 0) return 0;
int m = grid.length;
int n = grid[0].length;
int[] roots = new int[m*n];
int islands = 0;
for(int i=0; i<m; i++) {
for(int j=0; j<n; j++) {
if (grid[i][j] == '0') continue;
int id = i * n + j;
roots[id] = id;
islands ++;
if (i>0 && grid[i-1][j] == '1') {
int neighbor = (i-1) * n + j;
int nr = root(roots, neighbor);
if (nr != id) {
roots[nr] = id;
islands --;
}
}
if (j>0 && grid[i][j-1] == '1') {
int neighbor = i * n + (j-1);
int nr = root(roots, neighbor);
if (nr != id) {
roots[nr] = id;
islands --;
}
}
}
}
return islands;
}
private int root(int[] roots, int id) {
while (id != roots[id]) id = roots[roots[id]];
return id;
}
}
方法二:递归着色。
public class Solution {
private void check(char[][] grid, int row, int col) {
if (row < 0 || row >= grid.length || col < 0 || col >= grid[row].length ||grid[row][col] == '0') return;
grid[row][col] = '0';
check(grid, row-1, col);
check(grid, row+1, col);
check(grid, row, col-1);
check(grid, row, col+1);
}
public int numIslands(char[][] grid) {
int islands = 0;
for(int i=0; i<grid.length; i++) {
for(int j=0; j<grid[i].length; j++) {
if (grid[i][j] == '0') continue;
islands ++;
check(grid, i, j);
}
}
return islands;
}
}

本文介绍了一种计算二维网格中岛屿数量的方法。使用并查集和递归着色两种算法实现,适用于由'1'(陆地)和'0'(水域)组成的地图,其中岛屿由相邻的陆地水平或垂直连接而成。
&spm=1001.2101.3001.5002&articleId=51311628&d=1&t=3&u=080e37be8696491dac9476765bced6aa)
1503

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



