码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode200. Number of Islands

时间:2018-12-29 13:51:41      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:void   i++   color   数组   思路   length   ISE   一个   int   

题意:给一个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

标签:void   i++   color   数组   思路   length   ISE   一个   int   

原文地址:https://www.cnblogs.com/ctqchina/p/10195101.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!