<Atcoder - 151D> BFS最短路问题
https://atcoder.jp/contests/abc151/tasks/abc151_d
题意:
求任意两个可互相到达的点的最短路的最大值。
思路:
几乎是板子题,小范围数据直接暴力,碰到点就进行bfs,bfs停止的条件就是走不动了,也就是当前点(i, j)能走到的最远距离且是到达最远处的最短路径。不断维护到这个最远处的最短路径最大值即可。
AC代码:
#include <bits/stdc++.h>
using namespace std;
int n, m;
char a[25][25];
bool vis[25][25];
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
struct PP {
int x, y;
int res;
} s, q;
queue <PP> qua;
int ans;
void Init() {
scanf("%d %d", &n, &m);
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= m; j++) scanf(" %c", &a[i][j]);
}
}
bool Chk(int x, int y) {
if(vis[x][y] || x < 1 || x > n || y < 1 || y > m || a[x][y] == '#') return false;
return true;
}
int Bfs(int x, int y) {
int res = 0;
s.x = x, s.y = y, s.res = 0;
vis[x][y] = 1;
qua.push(s);
while(!qua.empty()) {
s = qua.front();
qua.pop();
res = max(res, s.res);
for(int i = 0; i < 4; i++) {
q.x = s.x + dx[i], q.y = s.y + dy[i];
if(!Chk(q.x, q.y)) continue;
q.res = s.res + 1;
vis[q.x][q.y] = 1;
qua.push(q);
}
}
return res;
}
int main() {
Init();
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= m; j++) {
if(a[i][j] == '.') {
memset(vis, 0, sizeof(vis));
while(!qua.empty()) qua.pop();
int tmp = Bfs(i, j);
ans = max(ans, tmp);
}
}
}
printf("%d\n", ans);
return 0;
}