LeetCode_DFS_中等_200.岛屿数量

x33g5p2x  于2022-04-22 转载在 其他  
字(1.5k)|赞(0)|评价(0)|浏览(250)

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

提示:
m == grid.length
n == grid[i].length
1 <= m, n <= 300
grid[i][j] 的值为 ‘0’ 或 ‘1’

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/number-of-islands

2.思路

(1)DFS
思路参考一文秒杀所有岛屿题目

3.代码实现(Java)

//思路1————DFS
class Solution {
    public int numIslands(char[][] grid) {
        //res保存岛屿数量,初始值为 0
        int res = 0;
        int m = grid.length;
        int n = grid[0].length;
        //遍历grid
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == '1') {
                    //发现一个岛屿
                    res++;
                    //使用DFS将该岛屿淹没(包括上下左右相邻的陆地)
                    dfs(grid, i, j);
                }
            }
        }
        return res;
    }

    public void dfs(char[][] grid, int i, int j) {
        int m = grid.length;
        int n = grid[0].length;
        //判断边界条件
        if (i < 0 || j < 0 || i >= m || j >= n) {
            return;
        }
        if (grid[i][j] == '0') {
            //当前位置已经是海水,则直接返回
            return;
        }
        //将当前位置变成海水,相当于使用数组visited记录遍历过的节点
        grid[i][j] = '0';
        //同时也淹没上下左右的陆地
        dfs(grid, i - 1, j);
        dfs(grid, i + 1, j);
        dfs(grid, i, j - 1);
        dfs(grid, i, j + 1);
    }
}

相关文章