leetcode200. Number of Islands

Posted ctqchina

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode200. Number of Islands相关的知识,希望对你有一定的参考价值。

题意:给一个0,1二维数组,求有多少块“1”(多个1上下左右相连算一块)

思路:DFS/BFS

DFS跑了6ms,BFS跑了12ms

DFS代码:

class Solution {
    
    int lenx =0 , leny= 0 ;
    int[] cx = {1,-1,0,0}, cy = {0,0,1,-1};
    void dfs(char[][] grid, int tx, int ty){
        
        if(tx <0 || tx >= lenx || ty<0 || ty >= leny) return;
        if(grid[tx][ty] == ‘0‘) return;
        grid[tx][ty] = ‘0‘;
        for(int i=0;i<4;i++)
            dfs(grid, tx+cx[i], ty+cy[i]);
    }
    
    
    public int numIslands(char[][] grid) {
        
        if(grid.length == 0) return 0;
        int ans = 0;
        lenx = grid.length; leny = grid[0].length;
        
        
        for(int i=0;i<lenx;i++){
            
            for(int j=0;j<leny;j++){
                
                if(grid[i][j] == ‘0‘) continue;
                ans++;
                dfs(grid,i,j);
        }
        }
        return ans;
    }
}

BFS代码:

class Solution {
    
     
    
    public int numIslands(char[][] grid) {
        
        if(grid.length == 0) return 0;
        int ans = 0;
        int lenx = grid.length, leny = grid[0].length;
        int[] cx = {1,-1,0,0}, cy = {0,0,1,-1};
        
        for(int i=0;i<lenx;i++){
            
            for(int j=0;j<leny;j++){
                
                if(grid[i][j] == ‘0‘) continue;
                LinkedList<Point> qu = new LinkedList<>();
                ans++;
                qu.add(new Point(i,j)); 
                grid[i][j] = ‘0‘;
                while(qu.isEmpty() == false){
                    Point now = qu.remove();
                    int x = now.x, y = now.y;
                    for(int k=0;k<4;k++){
                        int tx = x+cx[k], ty = y+cy[k];
                        if(tx <0 || tx >= lenx || ty<0 || ty >= leny) continue;
                        if(grid[tx][ty] == ‘0‘) continue;
                        grid[tx][ty] = ‘0‘;
                        qu.add(new Point(tx,ty));
                    }
                }
            }
        }
        
        return ans;
    }
}

 

以上是关于leetcode200. Number of Islands的主要内容,如果未能解决你的问题,请参考以下文章

leetcode200 Number of Islands

Leetcode 200. Number of Islands

[leetcode-200-Number of Islands]

leetcode 200. Number of Islands

leetcode--200. Number of Islands

[LeetCode] 200. Number of Islands(岛屿的数目)