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

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

相关推荐
im_AMBER1 天前
算法笔记 09
c语言·数据结构·c++·笔记·学习·算法·排序算法
凯芸呢1 天前
Java中的数组(续)
java·开发语言·数据结构·算法·青少年编程·排序算法·idea
寂静山林1 天前
UVa 1030 Image Is Everything
算法
AI柠檬1 天前
几种排序算法的实现和性能比较
数据结构·算法·c#·排序算法
weixin_429630261 天前
第6章 支持向量机
算法·机器学习·支持向量机
SweetCode1 天前
C++ 实现大数加法
开发语言·c++·算法
王哈哈^_^1 天前
【数据集】【YOLO】【目标检测】共享单车数据集,共享单车识别数据集 3596 张,YOLO自行车识别算法实战训推教程。
人工智能·算法·yolo·目标检测·计算机视觉·视觉检测·毕业设计
CodeWizard~1 天前
AtCoder Beginner Contest 430赛后补题
c++·算法·图论
大大dxy大大1 天前
机器学习-KNN算法示例
人工智能·算法·机器学习
关于不上作者榜就原神启动那件事1 天前
模拟算法乒乓球
开发语言·c++·算法