想看更多的解题报告: http://blog.csdn.net/wangjian8006/article/details/7870410
转载请注明出处:http://blog.csdn.net/wangjian8006
题目大意:给出一个m×n的地图,'#'是不能通过的,'.'是可以走的,问任意两点为'.'的最短距离中最长的
解题思路:先从任意一点'.'搜索,然后取一个最长的,再开始从这个点开始搜索,然后取最长的就是答案了
/*
Memory 5172K
Time 766MS
*/
#include <iostream>
#include <queue>
using namespace std;
#define MAXV 1010
char laby[MAXV][MAXV];
int n,m;
int firstx,firsty,ans;
int d[MAXV][MAXV];
int dx[4]={0,0,-1,1};
int dy[4]={-1,1,0,0};
void bfs(){
queue <int>q;
int tx,ty,i,vx,vy;
ans=0;
memset(d,-1,sizeof(d));
q.push(firstx);
q.push(firsty);
d[firstx][firsty]=0;
while(!q.empty()){
tx=q.front();q.pop();
ty=q.front();q.pop();
for(i=0;i<4;i++){
vx=tx+dx[i];
vy=ty+dy[i];
if(vx>=0 && vx<=m && vy>=0 && vy<=n && laby[vx][vy]=='.' && d[vx][vy]==-1){
q.push(vx);
q.push(vy);
d[vx][vy]=d[tx][ty]+1;
if(ans<d[vx][vy]){
ans=d[vx][vy];
firstx=vx;
firsty=vy;
}
}
}
}
}
int main(){
int i,j,flag;
int Case;
scanf("%d",&Case);
while(Case--){
scanf("%d%d\n",&n,&m);
for(i=0;i<m;i++) scanf("%s",laby[i]);
flag=1;
for(i=0;flag;i++){
for(j=0;j<n;j++)
if(laby[i][j]=='.'){
firstx=i,firsty=j,flag=0;
break;
}
}
bfs();
bfs();
printf("Maximum rope length is %d.\n",ans);
}
return 0;
}