leetcode 200-Number of Islands(medium)

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.

class Solution {
    public int numIslands(char[][] grid) {
        if(grid.length==0||grid[0].length==0) return 0;
        boolean[][] bool=new boolean[grid.length][grid[0].length];
        int land=0;
        for(int i=0;i<grid.length;i++){
            for(int j=0;j<grid[0].length;j++){
                if(bool[i][j]||grid[i][j]=='0') continue;
                expand(grid, i, j, bool);
                land++;
            }
        }
        return land;
    }
    public void expand(char[][] grid, int i, int j, boolean[][] bool){
        if(i<0||i>=grid.length||j<0||j>=grid[0].length||grid[i][j]=='0'||bool[i][j]) return;
        bool[i][j]=true;
        expand(grid,i-1,j,bool);
        expand(grid,i+1,j,bool);
        expand(grid,i,j-1,bool);
        expand(grid,i,j+1,bool);
    }
}

事实上没有必要用bool来记录是否访问过,直接对访问过的‘1’置‘0’即可。但如果用了bool来记录,就不要漏掉return条件bool[i][j]为true,否则已访问过的点还会不断相互访问下去,陷入死循环。

class Solution {
    public int numIslands(char[][] grid) {
        if(grid.length==0||grid[0].length==0) return 0;
        int len=0;
        for(int i=0;i<grid.length;i++){
            for(int j=0;j<grid[0].length;j++){
                if(grid[i][j]=='0') continue;
                expand(grid,i,j);
                len++;
            }
        }
        return len;
    }
    public void expand(char[][] grid, int i, int j){
        if(i<0||j<0||i>=grid.length||j>=grid[0].length||grid[i][j]=='0') return;
        grid[i][j]='0';
        expand(grid, i-1,j);
        expand(grid, i+1,j);
        expand(grid, i,j-1);
        expand(grid, i,j+1);
    }
}

猜你喜欢

转载自www.cnblogs.com/yshi12/p/9704694.html