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

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

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;
}

补充题目 蓝桥杯 -- 危险系数

P8604 [蓝桥杯 2013 国 C] 危险系数 - 洛谷

 

相关文章:

  • ArcGis和Super Map
  • 接入DeepSeek后,智慧园区安全调度系统的全面提升
  • 怎样从零基础开始学习大模型
  • Vue2/Vue3自定义指令
  • 从零开始构建一个语言模型中vocab_size(词汇表大小)的设定规则
  • v4l2子系统学习(一)V4L2应用程序编程
  • Python3测试开发面试题2
  • 在echarts的tooltip组件中使用vue3自定义组件
  • Spring Bean生命周期通俗讲解
  • VScode C语言学习开发环境;运行提示“#Include错误,无法打开源文件stdio.h”
  • php文件包含
  • C extern在函数声明中的作用
  • 各类数据质量等相关学习地址
  • vmware centos 10 stream boot 安装
  • 【算法】快排-786. 第k个数
  • 23. AI-大语言模型-DeepSeek
  • MySQL登录问题总结
  • 【Reasoning】LLaMA-Berry: Pairwise Optimization for O1-like Olympiad-Level Mathematical Reasoning
  • Linux 内核中的 container_of 宏:以 ipoib_rx_poll_rss 函数为例
  • Langchain vs. LlamaIndex:哪个在集成MongoDB并分析资产负债表时效果更好?
  • 全球最大汽车板供应商宝钢股份:汽车工业加速转型中材料商如何共舞?
  • 李强签署国务院令,公布修订后的《中华人民共和国植物新品种保护条例》
  • 市场监管总局:2024年查办商标、专利等领域违法案件4.4万件
  • 中方发布《不跪!》视频传递何种信息?外交部回应
  • 今年一季度全国社会物流总额达91万亿元,工业品比重超八成
  • 从咖啡节到话剧、演唱会,上海虹口“文旅商体展”联动促消费