算法提高课-搜索-多源BFS-AcWing 173. 矩阵距离:bfs、多源bfs
生活随笔
收集整理的這篇文章主要介紹了
算法提高课-搜索-多源BFS-AcWing 173. 矩阵距离:bfs、多源bfs
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目分析
來源:acwing
分析:
0表示住戶,1表示超市,這些超市是等價的。求每個住戶到達超市的最近距離。
多源bfs在做的時候,把所有超市的距離都初始化為0,然后壓入隊列。
ac代碼
#include<bits/stdc++.h> #define x first #define y second using namespace std; typedef pair<int,int> PII; const int N = 1010, M = N * N; int n, m; char g[N][N]; PII q[M]; int dist[N][N];void bfs(){memset(dist, -1, sizeof dist);int hh = 0, tt = -1;for(int i = 0; i < n; i++)for(int j = 0; j < m; j++)if(g[i][j] == '1'){q[++tt] = {i, j};dist[i][j] = 0;}int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};while(hh <= tt){PII 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) continue;if(dist[a][b] != -1) continue; // 如果遍歷過,則跳過dist[a][b] = dist[t.x][t.y] + 1;q[++tt] = {a,b};}}}int main(){cin >> n >> m;for(int i = 0; i < n; i ++) cin >> g[i];bfs();for(int i = 0; i < n; i ++){for(int j = 0; j< m; j ++)cout << dist[i][j] << " ";cout << endl;} }題目來源
https://www.acwing.com/problem/content/175/
總結
以上是生活随笔為你收集整理的算法提高课-搜索-多源BFS-AcWing 173. 矩阵距离:bfs、多源bfs的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 算法提高课-搜索-最短路模型-AcWin
- 下一篇: 算法提高课-搜索-最小步数模型-AcWi