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

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] 危险系数 - 洛谷

相关推荐
我爱C编程1 小时前
基于Qlearning强化学习的1DoF机械臂运动控制系统matlab仿真
算法
chao_7891 小时前
CSS表达式——下篇【selenium】
css·python·selenium·算法
chao_7892 小时前
Selenium 自动化实战技巧【selenium】
自动化测试·selenium·算法·自动化
YuTaoShao2 小时前
【LeetCode 热题 100】24. 两两交换链表中的节点——(解法一)迭代+哨兵
java·算法·leetcode·链表
怀旧,2 小时前
【数据结构】8. 二叉树
c语言·数据结构·算法
泛舟起晶浪2 小时前
相对成功与相对失败--dp
算法·动态规划·图论
地平线开发者2 小时前
地平线走进武汉理工,共建智能驾驶繁荣生态
算法·自动驾驶
IRevers3 小时前
【自动驾驶】经典LSS算法解析——深度估计
人工智能·python·深度学习·算法·机器学习·自动驾驶
前端拿破轮3 小时前
翻转字符串里的单词,难点不是翻转,而是正则表达式?💩💩💩
算法·leetcode·面试
凤年徐3 小时前
【数据结构与算法】203.移除链表元素(LeetCode)图文详解
c语言·开发语言·数据结构·算法·leetcode·链表·刷题