力扣热门100题之岛屿的数量(DFS/BFS经典题)

核心思路:

遍历每一个格子,遇到陆地就把它所在的整座岛全部淹掉(标记为 0),岛屿数量 +1

通俗解释

  1. 逐个格子扫一遍
  2. 碰到 1 说明发现一座新岛 ,count++
  3. 立刻用 DFS 把这座岛所有相连的 1 都改成 0(相当于淹掉)
  4. 继续扫,直到结束

这样每座岛只会被计数一次

完整代码实现:

java 复制代码
class Solution {
    public int numIslands(char[][] grid) {
        if(grid == null || grid.length == 0) return 0;

        int count = 0;
        int m = grid.length;
        int n = grid[0].length;

        for(int i = 0;i<m;i++){
            for(int j = 0;j<n;j++){
                // 找到一块陆地
                if(grid[i][j] == '1'){
                    count++;
                    // 把这座岛全部淹掉
                    dfs(grid,i,j);
                }
            }
        }
        return count;
    }

    public void dfs(char[][] grid,int i,int j){
        int m = grid.length;
        int n = grid[0].length;

        // 越界 或者 是水,直接返回
        if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == '0') {
            return;
        }

        // 淹掉
        grid[i][j] = '0';

        dfs(grid,i - 1,j);
        dfs(grid,i + 1,j);
        dfs(grid,i,j - 1);
        dfs(grid,i,j + 1);
    }
}
相关推荐
alphaTao6 小时前
LeetCode 每日一题 2026/10/12-2026/10/18
算法·leetcode
Cccp.1237 小时前
【leetcode】(十三)大数据处理
数据结构·算法·leetcode
Pniubi7 小时前
力扣70爬楼梯
数据结构·算法·leetcode
Navigator_Z1 天前
LeetCode //C - 1293. Shortest Path in a Grid with Obstacles Elimination
c语言·算法·leetcode
Nil2081 天前
leetcode 64最小路径和
算法·leetcode·职场和发展
Nil2081 天前
leetcode 72编辑距离
算法·leetcode·职场和发展
Nil2081 天前
leetcode 136只出现一次的数字
leetcode·哈希算法·散列表
垆边人似月.1 天前
删边使每个连通块权值和为 target
算法·深度优先·图论
局部有解1 天前
LeetCode Hot100 438 找到字符串中所有字母异位词
c++·算法·leetcode
Nil2081 天前
leetcode 75颜色分类
数据结构·算法·leetcode