200. 岛屿数量

2021-06-22 22:03:42 浏览数 (1)

给你一个由 '1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。 岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。 此外,你可以假设该网格的四条边均被水包围。 示例 1: 输入:grid = [ ["1","1","1","1","0"], ["1","1","0","1","0"], ["1","1","0","0","0"], ["0","0","0","0","0"] ] 输出:1 示例 2: 输入:grid = [ ["1","1","0","0","0"], ["1","1","0","0","0"], ["0","0","1","0","0"], ["0","0","0","1","1"] ] 输出:3

代码语言:javascript复制
class Solution {
    int res=0;
    public int numIslands(char[][] grid) {
        /**
        从 (i, j)=1 向此点的上下左右 (i 1,j),(i-1,j),(i,j 1),(i,j-1) 做深度搜索。
    终止条件:
        (i, j) 越过矩阵边界;
        grid[i][j] == 0,代表此分支已越过岛屿边界。
    搜索岛屿的同时,执行 grid[i][j] = '0',即将岛屿所有节点删除,以免之后重复搜索相同岛屿。
         */
         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;
    }

   public void dfs(char [][] grid,int row,int col){
       if(row<0||col<0||row>=grid.length||col>=grid[0].length||grid[row][col]=='0'){
           return ;//找到一个岛屿
       }
        //更新当前的为0
        grid[row][col]='0';
       //否则他是1 还是相连陆地
       dfs(grid,row 1,col);
       dfs(grid,row-1,col);
       dfs(grid,row,col-1);
       dfs(grid,row,col 1);
   }
}

0 人点赞