当前位置: 首页 > 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] 危险系数 - 洛谷

 


http://www.mrgr.cn/news/91701.html

相关文章:

  • 2526考研资料分享 百度网盘
  • 浅谈 — 分布式系统中的幂等性
  • ZLMediaKit Windows 编译指南
  • 千峰React:组件使用(1)
  • 【Quest开发】全身跟踪
  • 数仓搭建(hive):DWS层(服务数据层)
  • Jmeter连接数据库、逻辑控制器、定时器
  • leetcode203.移除链表元素
  • 【Java】泛型与集合篇 —— 泛型
  • SCANet代码解读
  • 【Elasticsearch】`nested`和`flattened`字段在索引时有显著的区别
  • 【DeepSeek系列】04 DeepSeek-R1:带有冷启动的强化学习
  • TCP和Http协议
  • PyTorch 源码学习:阅读经验 代码结构
  • 嵌入式音视频开发(三)直播协议及编码器
  • 【Java】泛型与集合篇 —— Set 接口
  • 前端常见面试题-2025
  • C语言——时基
  • Linux-----进程(多任务)
  • C#发送邮件