算法提高课-搜索-DFS之连通性模型-AcWing 1113. 红与黑:dfs和bfs两种做法
生活随笔
收集整理的這篇文章主要介紹了
算法提高课-搜索-DFS之连通性模型-AcWing 1113. 红与黑:dfs和bfs两种做法
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
題目分析
來源:acwing
分析:
ac代碼
dfs寫法
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)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 算法提高课-搜索-DFS之连通性模型-A
- 下一篇: 算法提高课-搜索-DFS之搜索顺序-Ac