leetcode-岛屿数量-99

题目要求

思路

1.使用广度优先遍历,将数组中所有为1的元素遍历一遍,遍历过程中使用递归,讲该元素的上下左右四个方向的元素值也置为0

2.统计一共执行过多少次,次数就是岛屿数量
代码实现

cpp 复制代码
class Solution {
public:
    int solve(vector<vector<char> >& grid) {
        int n = grid.size();
        int m = grid[0].size();
        int index = 0;
        for(int i = 0; i < n; i++)
        {
            for(int j = 0; j < m; j++)
            {
                if(grid[i][j] == '1')
                {
                    index++;
                    // cout << i << " " << j <<endl;
                    dfs(grid, i, j);
                }
            }
        }
        return index;
    }

    void dfs(vector<vector<char>>& grid, int i, int j)
    {
        if(grid[i][j] == '1')
            grid[i][j] = '0';

        if(i > 0 && grid[i-1][j] == '1')
            dfs(grid, i-1, j);
        if(j > 0 && grid[i][j-1] == '1')
            dfs(grid, i, j-1);
        if(i < grid.size() - 1 && grid[i+1][j] == '1')
            dfs(grid, i+1, j);
        if(j < grid[0].size() - 1 && grid[i][j+1] == '1')
            dfs(grid, i, j+1);
    }
};
相关推荐
tankeven2 分钟前
HJ101 排序
c++·算法
流云鹤3 分钟前
动态规划02
算法·动态规划
小白菜又菜12 分钟前
Leetcode 236. Lowest Common Ancestor of a Binary Tree
python·算法·leetcode
不想看见40412 分钟前
01 Matrix 基本动态规划:二维--力扣101算法题解笔记
c++·算法·leetcode
多恩Stone16 分钟前
【3D-AICG 系列-12】Trellis 2 的 Shape VAE 的设计细节 Sparse Residual Autoencoding Layer
人工智能·python·算法·3d·aigc
踢足球092929 分钟前
寒假打卡:2026-2-23
数据结构·算法
田里的水稻1 小时前
FA_建图和定位(ML)-超宽带(UWB)定位
人工智能·算法·数学建模·机器人·自动驾驶
Navigator_Z1 小时前
LeetCode //C - 964. Least Operators to Express Number
c语言·算法·leetcode
郝学胜-神的一滴1 小时前
Effective Modern C++ 条款40:深入理解 Atomic 与 Volatile 的多线程语义
开发语言·c++·学习·算法·设计模式·架构
摸鱼仙人~1 小时前
算法题避坑指南:数组/循环范围的 `+1` 到底什么时候加?
算法