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

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

算法提高课-搜索-DFS之连通性模型-AcWing 1113. 红与黑:dfs和bfs两种做法

發(fā)布時(shí)間:2025/4/5 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 算法提高课-搜索-DFS之连通性模型-AcWing 1113. 红与黑:dfs和bfs两种做法 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

題目分析


來源:acwing

分析:

ac代碼

dfs寫法

  • dfs搜的時(shí)候需要dfs(下一狀態(tài))
  • 本題統(tǒng)計(jì)連續(xù)的黑色格子數(shù)量 :從(x, y) – > (a ,b) 擴(kuò)展時(shí), cnt += dfs(a,b)即可。
  • #include<bits/stdc++.h> using namespace std;const int N = 30;char g[N][N]; bool st[N][N]; int n, m;int dfs(int x, int y){int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};st[x][y] = true;int cnt =1;for(int i = 0; i < 4; i ++){int a = x + dx[i], b = y + dy[i];if( a < 0 || a >= n || b < 0 || b >= m || st[a][b] || g[a][b] == '#') continue;cnt += dfs(a,b);}return cnt; }int main(){while(cin >> m >> n, n || m){memset(st, 0, sizeof st);for(int i = 0; i< n ;i ++) cin >> g[i];for(int i = 0; i < n; i ++)for(int j = 0; j< m; j ++)if( g[i][j] == '@'){cout << dfs(i ,j) << endl;}} }

    bfs寫法:

    #include<bits/stdc++.h> using namespace std; typedef pair<int,int> PII; #define x first #define y second const int N = 30, M = N * N; PII q[M]; char g[N][N]; bool st[N][N]; int n, m;int bfs(int sx, int sy){int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};int hh = 0, tt = 0;q[0] = {sx, sy};st[sx][sy] = true;int cnt =1;while( hh <= tt){auto t = q[ hh ++];for(int i = 0; i < 4; i ++){int a = t.x + dx[i], b = t.y + dy[i];if( a < 0 || a >= n || b < 0 || b >= m || st[a][b] || g[a][b] == '#') continue;cnt ++;st[a][b] = true;q[++ tt] = {a,b};}}return cnt; }int main(){while(cin >> m >> n, n || m){memset(st, 0, sizeof st);for(int i = 0; i< n ;i ++) cin >> g[i];for(int i = 0; i < n; i ++)for(int j = 0; j< m; j ++)if( g[i][j] == '@'){cout << bfs(i ,j) << endl;}} }

    題目來源

    https://www.acwing.com/problem/content/1115/

    總結(jié)

    以上是生活随笔為你收集整理的算法提高课-搜索-DFS之连通性模型-AcWing 1113. 红与黑:dfs和bfs两种做法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。