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

99 统计岛屿的数量 c++

99. 岛屿数量

cpp 复制代码
#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] 危险系数 - 洛谷

相关推荐
黄昏ivi1 小时前
电力系统最小惯性常数解析
算法
独家回忆3641 小时前
每日算法-250425
算法
烁3471 小时前
每日一题(小白)模拟娱乐篇33
java·开发语言·算法
Demons_kirit2 小时前
LeetCode 2799、2840题解
算法·leetcode·职场和发展
软行2 小时前
LeetCode 每日一题 2845. 统计趣味子数组的数目
数据结构·c++·算法·leetcode
永远在Debug的小殿下2 小时前
查找函数【C++】
数据结构·算法
我想进大厂2 小时前
图论---染色法(判断是否为二分图)
数据结构·c++·算法·深度优先·图论
油泼辣子多加2 小时前
【风控】稳定性指标PSI
人工智能·算法·金融
雾月553 小时前
LeetCode 1292 元素和小于等于阈值的正方形的最大边长
java·数据结构·算法·leetcode·职场和发展
知来者逆5 小时前
计算机视觉——速度与精度的完美结合的实时目标检测算法RF-DETR详解
图像处理·人工智能·深度学习·算法·目标检测·计算机视觉·rf-detr