力扣200. 岛屿数量(DFS)

Problem: 200. 岛屿数量

文章目录

题目描述

思路及解法

1.遍历矩阵grid的每一个位置;若某个位置为'1'则将用于记录岛屿数量的变量count++,并调用dfs函数;

2.dfs函数实现:

2.1.若当前grid位置为'0'则直接返回;若超出了grid的边界也直接返回;

2.2.若当前位置为'1'则将其变为海水即覆盖为'0',并向其上下左右方向DFS

复杂度

时间复杂度:

O ( M × N ) O(M \times N) O(M×N);其中 M M M和 N N N分别为举证grid的行数与列数

空间复杂度:

O ( M × N ) O(M \times N) O(M×N)

Code

cpp 复制代码
class Solution {
public:
    /**
     * Use DFS to get the maximum number of islands
     *
     * @param grid Island array
     * @return int
     */
    int numIslands(vector<vector<char>>& grid) {
        int count = 0;
        int m = grid.size();
        int n = grid[0].size();
        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;
    }

    /**
     * DFS implementation function
     *
     * @param grid Island array
     * @param i Index subscript
     * @param j Index subscript
     */
    void dfs(vector<vector<char>>& grid, int i, int j) {
        int m = grid.size();
        int n = grid[0].size();
        // out of index
        if (i < 0 || j < 0 || i >= m || j >= n) {
            return;
        }
        // It's already sea water
        if (grid[i][j] == '0') {
            return;
        }
        // Turn grid[i][j] into seawater
        grid[i][j] = '0';
        // Flood the land up and down
        dfs(grid, i + 1, j);
        dfs(grid, i, j + 1);
        dfs(grid, i - 1, j);
        dfs(grid, i, j - 1);
    }
};
相关推荐
Jerry1 小时前
LeetCode 101. 对称二叉树
算法
可编程芯片开发2 小时前
基于MPPT最大功率跟踪的离网光伏发电系统Simulink建模与仿真
算法
AI科技星2 小时前
线性算子不是空间映射函数,是全域双螺旋场之间拉伸、旋转、耦合、坍缩的跨空间标准化变换载体《全域数学vs传统数学:人类文明进阶200讲》第80讲
线性代数·算法·矩阵·数据挖掘·回归·乖乖数学·全域数学
米罗篮2 小时前
矩阵快速幂 (Exponentiation By Squaring Applied To Matrices)
c++·线性代数·算法·矩阵
dream_home84073 小时前
图像算法模型NPU适配与算法服务实战指南
人工智能·python·算法·npu 图像服务
大鱼>3 小时前
多宠物家庭智能管理平台:云端架构与多设备协同实战
python·算法·iot·宠物
To_OC4 小时前
LC 22 括号生成:刷完这道题,我终于搞懂回溯剪枝了
javascript·算法·leetcode
To_OC4 小时前
LC 39 组合总和:回溯入门必刷题,我踩过的两个坑都在这了
javascript·算法·leetcode
数字杂技师4 小时前
每条推荐都很准,为什么我还是越刷越无聊?
算法
兰令水4 小时前
hot100【acm版】【2026.7.14打卡-java版本】
java·数据结构·算法·leetcode·面试