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

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

相关推荐
东方芷兰2 小时前
算法笔记 04 —— 算法初步(下)
c++·笔记·算法
JNU freshman2 小时前
图论 之 迪斯科特拉算法求解最短路径
算法·图论
青松@FasterAI3 小时前
【NLP算法面经】本科双非,头条+腾讯 NLP 详细面经(★附面题整理★)
人工智能·算法·自然语言处理
Emplace3 小时前
ABC381E题解
c++·算法
若兰幽竹4 小时前
【机器学习】衡量线性回归算法最好的指标:R Squared
算法·机器学习·线性回归
居然有人6544 小时前
23贪心算法
数据结构·算法·贪心算法
SylviaW085 小时前
python-leetcode 37.翻转二叉树
算法·leetcode·职场和发展
h^hh5 小时前
洛谷 P3405 [USACO16DEC] Cities and States S(详解)c++
开发语言·数据结构·c++·算法·哈希算法
玦尘、5 小时前
位运算实用技巧与LeetCode实战
算法·leetcode·位操作