200. Number of Islands
2017-01-16 本文已影响293人
evil_ice
题目200. 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
1,BFS+DFS
public class Solution {
private int m;
private int n;
public int numIslands(char[][] grid) {
if(grid == null){
return 0;
}
m = grid.length;
if(m == 0){
return 0;
}
n = grid[0].length ;
if(n == 0){
return 0;
}
int nums = 0;
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
if(grid[i][j] == '1'){
dfs(i,j,grid);
nums++;
}
}
}
return nums;
}
private void dfs(int i, int j, char[][] grid){
if(i < 0 || j < 0 || i >= m || j >= n || grid[i][j] == '0'){
return;
}
grid[i][j] = '0';
dfs(i-1,j,grid);
dfs(i+1,j,grid);
dfs(i,j-1,grid);
dfs(i,j+1,grid);
}
}
2,BFS+并查集
public class Solution {
private int count;
private int[] parents;
//初始化并查集
public void initUnionFind(int m, int n, char[][] grid){
parents = new int[m*n];
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
if(grid[i][j] == '1'){
count++;
}
parents[i*n+j] = i*n+j;
}
}
}
public int find(int idx){
while(idx != parents[idx]){
//在查找的过程中压缩路径,减少查找的次数
parents[idx] = parents[parents[idx]];
idx = parents[idx];
}
return idx;
}
public void union(int p, int q){
int pRoot = find(p);
int qRoot = find(q);
//两个元素的根不同,则合并
if(pRoot != qRoot){
parents[qRoot] = pRoot;
count--;
}
}
public boolean isConnected(int p, int q){
int pRoot = find(p);
int qRoot = find(q);
//两点不连通
if(pRoot != qRoot){
return false;
}
return false;
}
public int numIslands(char[][] grid) {
if(grid == null || grid.length == 0){
return 0;
}
int m = grid.length;
if(grid[0] == null || grid[0].length == 0){
return 0;
}
int n = grid[0].length;
initUnionFind(m,n,grid);
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
if(grid[i][j] == '0'){
continue;
}
int cur = i*n+j;
if(i > 0 && grid[i-1][j] == '1'){
union(cur,cur-n);
}
if(i < m-1 && grid[i+1][j] == '1'){
union(cur,cur+n);
}
if(j > 0 && grid[i][j-1] == '1'){
union(cur, cur-1);
}
if(j < n-1 && grid[i][j+1] == '1'){
union(cur,cur+1);
}
}
}
return count;
}
}