力扣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);
    }
};
相关推荐
卷福同学2 小时前
【养虾日记】Openclaw操作浏览器自动化发文
人工智能·后端·算法
春日见3 小时前
如何入门端到端自动驾驶?
linux·人工智能·算法·机器学习·自动驾驶
图图的点云库3 小时前
高斯滤波实现算法
c++·算法·最小二乘法
一叶落4384 小时前
题目:15. 三数之和
c语言·数据结构·算法·leetcode
老鱼说AI5 小时前
CUDA架构与高性能程序设计:异构数据并行计算
开发语言·c++·人工智能·算法·架构·cuda
罗湖老棍子5 小时前
【例 1】数列操作(信息学奥赛一本通- P1535)
数据结构·算法·树状数组·单点修改 区间查询
big_rabbit05025 小时前
[算法][力扣222]完全二叉树的节点个数
数据结构·算法·leetcode
张李浩6 小时前
Leetcode 15三题之和
算法·leetcode·职场和发展
2301_793804697 小时前
C++中的适配器模式变体
开发语言·c++·算法
x_xbx7 小时前
LeetCode:206. 反转链表
算法·leetcode·链表