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

代码随想录-- 第一天图论 --- 岛屿的数量

99 统计岛屿的数量 c++

99. 岛屿数量

#include <iostream>
#include <vector>
#include <queue>

using namespace std;

struct MGraph {
    int numVertices, numEdges;
    vector<vector<int>> Edge;
};

int dir[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};

void dfs(MGraph& mGraph, vector<vector<bool>>& visited, int x, int y) {
    for (int i = 0; i < 4; ++i) {
        int nextx = x + dir[i][0];
        int nexty = y + dir[i][1];
        if (nextx >= 0 && nextx < mGraph.Edge.size() && 
            nexty >= 0 && nexty < mGraph.Edge[0].size() && 
            !visited[nextx][nexty] && mGraph.Edge[nextx][nexty] == 1) {
            visited[nextx][nexty] = true;
            dfs(mGraph, visited, nextx, nexty);
        }
    }
}

void bfs(MGraph& mGraph, vector<vector<bool>>& visited, int x, int y) {
    queue<pair<int, int>> q;
    visited[x][y] = true;
    q.push({x, y});

    while (!q.empty()) {
        auto [curx, cury] = q.front();
        q.pop();

        for (int i = 0; i < 4; ++i) {
            int nextx = curx + dir[i][0];
            int nexty = cury + dir[i][1];

            if (nextx >= 0 && nextx < mGraph.Edge.size() && 
                nexty >= 0 && nexty < mGraph.Edge[0].size() && 
                !visited[nextx][nexty] && mGraph.Edge[nextx][nexty] == 1) {
                visited[nextx][nexty] = true;
                q.push({nextx, nexty});
            }
        }
    }
}

int main() {
    int M, N;
    cin >> M >> N;

    MGraph mGraph;
    mGraph.Edge.resize(M, vector<int>(N));

    for (int i = 0; i < M; ++i) {
        for (int j = 0; j < N; ++j) {
            cin >> mGraph.Edge[i][j];
        }
    }

    vector<vector<bool>> visited(M, vector<bool>(N, false));
    int result = 0;

    for (int i = 0; i < M; ++i) {
        for (int j = 0; j < N; ++j) {
            if (!visited[i][j] && mGraph.Edge[i][j] == 1) {
                result++;
                dfs(mGraph, visited, i, j); // 可以替换为 bfs 如果需要广度优先搜索
            }
        }
    }

    cout << result << endl;
    return 0;
}


http://www.kler.cn/a/553825.html

相关文章:

  • 【SQL】多表查询案例
  • 解锁机器学习核心算法 | 决策树:机器学习中高效分类的利器
  • Python 性能剖析利器:DTrace 与 SystemTap 深度指南
  • PHP旅游门票预订系统小程序源码
  • 定期自动统计大表执行情况
  • SOME/IP--协议英文原文讲解9
  • JavaScript中内置对象
  • JVM内存管理笔记
  • 深入HBase——Bigtable
  • 数学函数(C#、Lua 、Unity)
  • React通用登录/注销功能实现方案(基于shadcn/ui)
  • 什么是语料清洗、预训练、指令微调、强化学习、内容安全; 什么是megatron,deepspeed,vllm推理加速框架
  • Hot100 图论
  • Redis如何解决大Key问题
  • Java面试第二山!《计算机网络》!
  • 为 ollama 服务增加 apikey 进行访问控制保护
  • 网络分析仪E5071C的回波损耗测量
  • 安心联车辆管理系统在汽车金融领域的应用
  • C#项目05-猜数字多线程
  • DeepSeek服务器繁忙 多种方式继续优雅的使用它