200. Number of Islands

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

你可能感兴趣的:(200. Number of Islands)