200. 岛屿数量 dfs

200. 岛屿数量

难度 中等

给你一个由 '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

提示:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 300
  • grid[i][j] 的值为 '0''1'

dfs思路 :

遍历数组的每个元素,若是 ‘1’ 并且 没有被遍历过 才能进入dfs进行遍历 而dfs里会对这个结点的四个方向都进行遍历, 知道连通的所有’1’并且都会置为遍历过的状态 跳出dfs sum++(岛屿数加1) , 继续遍历二维数组寻找下一个入口

下面进行设置遍历过状态是通过boolean数组设置的

class Solution {
 public int numIslands(char[][] grid) {

     boolean[][] bool = new boolean[grid.length][grid[0].length];
     int sum=0;
     //遍历二维数组  让所有的点有机会进入dfs
     for(int i=0; i<grid.length;i++){
         for(int j=0;j<grid[0].length;j++){
             if(grid[i][j]=='1'&&!bool[i][j]){
                 dfs(grid,i,j,bool);
                 sum++;
             }
         }
     }
     return sum;


 }

 void dfs(char[][] grid,int i ,int j,boolean[][] bool){
     //截止条件  
     //筛选条件 四个方向都能走  进行筛选
     for(int[] location : allLocation(i,j,grid.length,grid[0].length)){
         //筛选
         if( grid[location[0]][location[1]]=='1' && !bool[location[0]][location[1]] ){
             bool[location[0]][location[1]]=true; //设置为走过的 true  不可再走
             dfs(grid,location[0],location[1],bool);
         }
     }

 }
 List<int[]> allLocation(int i,int j,int x,int y){
     List<int[]> res =new ArrayList<int[]>();
     if(i+1<x) res.add(new int[]{i+1,j});//向下不出界
     if(j+1<y) res.add(new int[]{i,j+1});//向右
     if(i-1>=0) res.add(new int[]{i-1,j});//向上
     if(j-1>=0) res.add(new int[]{i,j-1});//向左
     return res;
 }
}

官方题解 dfs

与上面的题解的不同之处是通过 遍历过就设置为’1’ 的方式来替代上面的boolean数组

并且在找下一步路径上也进行了优化 快了许多 !!

class Solution {
 void dfs(char[][] grid, int r, int c) {
     int nr = grid.length;
     int nc = grid[0].length;

     if (r < 0 || c < 0 || r >= nr || c >= nc || grid[r][c] == '0') {
         return;
     }

     grid[r][c] = '0';
     dfs(grid, r - 1, c);
     dfs(grid, r + 1, c);
     dfs(grid, r, c - 1);
     dfs(grid, r, c + 1);
 }

 public int numIslands(char[][] grid) {
     if (grid == null || grid.length == 0) {
         return 0;
     }

     int nr = grid.length;
     int nc = grid[0].length;
     int num_islands = 0;
     for (int r = 0; r < nr; ++r) {
         for (int c = 0; c < nc; ++c) {
             if (grid[r][c] == '1') {
                 ++num_islands;
                 dfs(grid, r, c);
             }
         }
     }

     return num_islands;
 }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值