就相当于求树的直径,两次bfs。
#include <bits/stdc++.h>
using namespace std;
int b1[5] = {0,0,0,1,-1};
int b2[5] = {0,1,-1,0,0};
bool vis[1010][1010];
char a1[1010][1010];
int ans = 0, maxx = 0, maxy = 0, max1 = 0;
int dfs(int x, int y){
vis[x][y] = 1;
for(int i = 1; i <= 4; i ++){
int x1 = x+b1[i], y1 = y+b2[i];
if(!vis[x1][y1]&&a1[x1][y1]=='.'){
dfs(x1,y1);
}
}
}
struct node{
int x, y, step;
};
bool vis2[1010][1010];
queue <node> q1;
int bfs(int x, int y){
while(!q1.empty()) q1.pop();
memset(vis2, 0, sizeof vis2);
q1.push((node){x,y,0});
while(!q1.empty()){
node t = q1.front();
q1.pop();
if(t.step > ans) ans = t.step, maxx = t.x, maxy = t.y;
for(int i = 1; i <= 4; i ++){
int x1 = t.x+b1[i], y1 = t.y+b2[i];
if(!vis2[x1][y1]&&a1[x1][y1]=='.'){
q1.push((node){x1,y1,t.step+1});
vis2[x1][y1] = 1;
}
}
}
}
int main(){
int n, m;
scanf("%d%d", &n, &m);
for(int i = 1; i <= n; i ++)
scanf("%s", a1[i]+1);
for(int i = 1; i <= n; i ++)
a1[i][m+1] = '#';
for(int i = 1; i <= n; i ++){
for(int j = 1; j <= m; j ++){
if(!vis[i][j]&&a1[i][j] == '.'){
dfs(i,j);
bfs(i,j);
bfs(maxx,maxy);
max1 = max(max1, ans);
}
}
}
printf("%d", max1);
return 0;
}