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;
}
}