当前位置: 首页 > news >正文

代码随想录算法【Day52】

Day51

101. 孤岛的总面积

思路

从周边找到陆地然后 通过 dfs或者bfs 将周边靠陆地且相邻的陆地都变成海洋,然后再去重新遍历地图 统计此时还剩下的陆地

代码

#include <iostream>
#include <vector>
using namespace std;
int dir[4][2] = {-1, 0, 0, -1, 1, 0, 0, 1}; // 保存四个方向
int count; // 统计符合题目要求的陆地空格数量
void dfs(vector<vector<int>>& grid, int x, int y) {
    grid[x][y] = 0;
    count++;
    for (int i = 0; i < 4; i++) { // 向四个方向遍历
        int nextx = x + dir[i][0];
        int nexty = y + dir[i][1];
        // 超过边界
        if (nextx < 0 || nextx >= grid.size() || nexty < 0 || nexty >= grid[0].size()) continue;
        // 不符合条件,不继续遍历
        if (grid[nextx][nexty] == 0) continue;

        dfs (grid, nextx, nexty);
    }
    return;
}

int main() {
    int n, m;
    cin >> n >> m;
    vector<vector<int>> grid(n, vector<int>(m, 0));
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            cin >> grid[i][j];
        }
    }

    // 从左侧边,和右侧边 向中间遍历
    for (int i = 0; i < n; i++) {
        if (grid[i][0] == 1) dfs(grid, i, 0);
        if (grid[i][m - 1] == 1) dfs(grid, i, m - 1);
    }
    // 从上边和下边 向中间遍历
    for (int j = 0; j < m; j++) {
        if (grid[0][j] == 1) dfs(grid, 0, j);
        if (grid[n - 1][j] == 1) dfs(grid, n - 1, j);
    }
    count = 0;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (grid[i][j] == 1) dfs(grid, i, j);
        }
    }
    cout << count << endl;
}

相关文章:

  • SWAT| 水文 | SWAT模型(四):气象数据库制备(附Python代码)
  • 【Pandas】pandas Series sample
  • LeeCode题库第二十八题
  • 使用Open WebUI下载的模型文件(Model)默认存放在哪里?
  • Python strip() 方法详解:用途、应用场景及示例解析(中英双语)
  • react(9)-redux
  • Java四大框架深度剖析:MyBatis、Spring、SpringMVC与SpringBoot
  • react 踩坑记 too many re-renders.
  • Three.js 快速入门教程【七】常见几何体类型
  • ROS 2入门 - 机器人操作系统ROS2的安装
  • Mac下Python版本管理,适用于pyenv不起作用的情况
  • Dify怎么创建数据交易的智能体
  • [GESP202406 六级] 二叉树
  • [C++]使用纯opencv部署yolov12目标检测onnx模型
  • 开启开源新时代:DeepSeek引领人工智能技术开放化
  • YOLOv8与BiFormer注意力机制的融合:提升多场景目标检测性能的研究
  • Visual studio 2022 将打开文件的方式由单击改为双击
  • Java 数学函数库
  • 【电机控制器】ESP32-C3语言模型——豆包
  • k8s容器运行时环境选型指南
  • 全国35城居民对公共服务满意度“打分”,上海多项指标居首
  • 外交部:将持续便利中外人员往来,让“中国游”金字招牌更加闪耀
  • 广东茂名高州市山体滑坡已致3死1失联,搜救仍在继续
  • 世卫大会中国代表团:中国深入参与全球卫生治理,为构建人类卫生健康共同体贡献中国力量
  • 从《缶翁的世界》看吴昌硕等湖州籍书画家对海派的影响
  • 上海小学生暑(寒)托班会增设开办期数、延长办班时间吗?团市委回应