写bug的小杨

导航

岛屿数量——BFS / DFS对比

DFS 解法

class Solution {
    public int numIslands(char[][] grid) {
         int count=0;
         for(int i=0;i<grid.length;i++){
             for(int j=0;j<grid[0].length;j++){
                 if(grid[i][j]=='1'){
                    dfs(grid,i,j);
                    count++;
                 }
                 
             }
         }
         return count;
    }
    //DFS深度优先遍历
    public static void dfs(char[][] grid,int i,int j){                   
                if(i>=0&&i<grid.length&&j>=0&&j<grid[0].length&&grid[i][j]=='1')    {
                    grid[i][j]='0'; 
                    dfs(gird,i,j-1); 
                    dfs(grid,i-1,j); 
                    dfs(grid,i+1,j); 
                    dfs(gird,i,j+1);                 
                }                        
        }
    }
}   

 

 

 

BFS 解法

class Solution {
    public int numIslands(char[][] grid) {
         int count=0;
         for(int i=0;i<grid.length;i++){
             for(int j=0;j<grid[0].length;j++){
                 if(grid[i][j]=='1'){
                    bfs(grid,i,j);
                    count++;
                 }
                 
             }
         }
         return count;
    }
    //BFS 广度优先遍历
    public static void bfs(char[][] grid,int i,int j){
        Queue<int[]> queue=new LinkedList<>();
        queue.add(new int[]{i,j});
        while(!queue.isEmpty()){
                int[] cur=queue.poll();
                i=cur[0];
                j=cur[1];
                if(i>=0&&i<grid.length&&j>=0&&j<grid[0].length&&grid[i][j]=='1'){
                    grid[i][j]='0'; 
                    queue.add(new int[]{i,j-1}); 
                    queue.add(new int[]{i-1,j}); 
                    queue.add(new int[]{i+1,j}); 
                    queue.add(new int[]{i,j+1});                 
                }                        
        }
    }
}

  

 

posted on 2021-01-20 22:45  迷途的小狗  阅读(74)  评论(0编辑  收藏  举报