If you know how to solve 827. Making A Large Island, then this one is a piece of cake:

class Solution {
    private int res =0;
    int m,n;
    public int numIslands(char[][] grid) {
        if(grid==null||grid.length==0)
            return 0;
        m = grid.length;
        n = grid[0].length;
        
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                if(grid[i][j]=='1'){
                    res++;
                    dfs(grid, i, j);
                }
            }
        }
        
        return res;
    }
    
    private int[][] dirs={{0,1},{0,-1},{-1,0},{1,0}};
    private void dfs(char[][] grid, int i, int j){
        grid[i][j]='0';
        for(int[] dir:dirs){
            int x = i+dir[0],y=j+dir[1];
            if(check(grid, x,y))
                dfs(grid, x, y);
        }
        
    }
    
    private boolean check(char[][] grid, int i, int j){
        if(i<0||i>=m||j<0||j>=n || grid[i][j]=='0')
            return false;
        return true;
    }
}

 

posted on 2022-03-08 08:33  阳光明媚的菲越  阅读(20)  评论(0编辑  收藏  举报