当前位置: 首页 > 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.lryc.cn/news/539975.html

相关文章:

  • Mybatis MyBatis框架的缓存 一级缓存
  • Weboffice在线Word权限控制:限制编辑,只读、修订、禁止复制等
  • RT-Thread+STM32L475VET6实现呼吸灯
  • 【Web前端开发精品课 HTML CSS JavaScript基础教程】第二十四章课后题答案
  • 记录 pycharm 无法识别提示导入已有的模块解决方案 No module named ‘xxx‘
  • 网工项目实践2.6 广域网需求分析及方案制定
  • 【架构】分层架构 (Layered Architecture)
  • 玩客云 IP查找
  • Android - Handler使用post之后,Runnable没有执行
  • MyBatis-Plus之通用枚举
  • 基于Spring Boot的图书管理系统设计与实现(LW+源码+讲解)
  • 如何在 VS Code 中快速使用 Copilot 来辅助开发
  • 12.1 Android中协程的基本使用
  • 【黑马点评优化】2-Canel实现多级缓存(Redis+Caffeine)同步
  • php-fpm
  • Python3测试开发面试题2
  • qt + opengl 给立方体增加阴影
  • Webpack,Vite打包的理解
  • Vue 3 30天精进之旅:Day 25 - PWA支持
  • 机器学习-生命周期
  • 大道至简 少字全意 易经的方式看 缓存 mybatis缓存 rendis缓存场景 案例
  • 如何使用 Flutter DevTools 和 PerformanceOverlay 监控性能瓶颈
  • TS中Any和Unknown有什么区别
  • 【Mpx】-环境搭建项目创建(一)
  • PyQt加载UI文件
  • Java面试第二山!《计算机网络》!
  • Mysql基础语句
  • 连接池Java导包
  • 一些耳朵起茧子的名词解释
  • HBuilderX中,VUE生成随机数字,vue调用随机数函数