日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

[蓝桥杯2018初赛]全球变暖-dfs,bfs,连通块

發布時間:2023/12/4 编程问答 45 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [蓝桥杯2018初赛]全球变暖-dfs,bfs,连通块 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.




解題思路:
bfs:遍歷所有未遍歷過的陸地,通過bfs計算出當前位置連通陸地的數量cnt,以及被淹沒陸地的數量bound,若cnt == bound表示完整淹沒的一個島嶼

dfs:將連通塊全部標記,如果這個連通塊全部都會淹沒,則答案+1,如果這個連通塊里面有無法被淹沒的,就不+1

bfs代碼如下:

#include <iostream> #include <queue> #include <cstring> using namespace std; typedef pair<int, int>PII; #define x first #define y second const int N = 1010; char g[N][N]; int res = 0; bool st[N][N]; int n;int dx[] = {0, 0, 1, -1}, dy[] = {1, -1, 0, 0};void bfs(int x, int y, int &cnt, int &bound) {queue<PII>q;q.push({x, y});st[x][y] = true;while (q.size()) {bool is_bound = false;PII t = q.front();cnt++;q.pop();for (int i = 0; i < 4; i++) {int xx = t.x + dx[i], yy = t.y + dy[i];if (xx < 0 || xx >= n || yy < 0 || yy >= n)continue;if (g[xx][yy] == '.') {is_bound = true;continue;}if (st[xx][yy])continue;st[xx][yy] = true;q.push({xx, yy});}if (is_bound) {bound++;}}}int main() {cin >> n;for (int i = 0; i < n; i++)cin >> g[i];for (int i = 0; i < n; i++)for (int j = 0; j < n; j++) {if (g[i][j] == '#' && !st[i][j]) {int bound = 0, cnt = 0;bfs(i, j, cnt, bound);if (cnt == bound)res++;}}cout << res << endl;return 0; }

dfs代碼如下:

#include <iostream> using namespace std; const int N = 1010; char g[N][N]; int ans;bool flag;int dx[] = {0, 0, 1, -1}, dy[] = {1, -1, 0, 0}; bool vis[N][N];void dfs(int x, int y) {if (g[x + 1][y] == '#' && g[x - 1][y] == '#' && g[x][y + 1] == '#' && g[x][y - 1] == '#')flag = true;///上下左右都是陸地,不會淹沒for (int i = 0; i < 4; i++) {int xx = x + dx[i], yy = y + dy[i];if (g[xx][yy] == '#' && !vis[xx][yy]) {vis[xx][yy] = true;dfs(xx, yy);}} }int main() {int n;cin >> n;for (int i = 1; i <= n; i++)cin >> g[i];for (int i = 1; i <= n; i++)for (int j = 1; j <= n; j++) {if (g[i][j] == '#' && !vis[i][j]) {flag = false;dfs(i, j);if (!flag)ans++;}}cout << ans << endl;return 0; }

總結

以上是生活随笔為你收集整理的[蓝桥杯2018初赛]全球变暖-dfs,bfs,连通块的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。