同样是利用广搜来做,唯一不同是有了两个起点,并且还是遍历起点来进行判断,比较哪一种搭配最适合或走的步数最少,btw,如果出现runtime error情况,一般是数组或者结构体数组开小了
#include<queue>
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=10+5;
const int INF=10000000;
int vis[maxn][maxn];
char g[maxn][maxn];
int n,m;
int d[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
struct node{
int x,y,step;
}a[105];
int fun()
{
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
{
if(g[i][j]=='#'&&vis[i][j]==0)
return 0;
}
return 1;
}
int BFS(node ax,node ay)
{
node th;
queue<node> q;
q.push(ax);q.push(ay);
vis[ax.x][ax.y]=vis[ay.x][ay.y]=1;
while(!q.empty())
{
th=q.front();q.pop();
for(int i=0;i<4;i++)
{
node rh=th;
rh.x+=d[i][0];rh.y+=d[i][1];
if(rh.x>=0&&rh.x<n&&rh.y>=0&&rh.y<m&&g[rh.x][rh.y]=='#'&&vis[rh.x][rh.y]==0)
{
rh.step++;
q.push(rh);
vis[rh.x][rh.y]=1;
}
}
}
return th.step;//返回step的值
}
int main()
{
int t;
//freopen("I.txt","r",stdin);
scanf("%d",&t);
for(int c=1;c<=t;c++)
{
scanf("%d %d",&n,&m);
int k=0;
for(int i=0;i<n;i++)
{
scanf("%s",g[i]);
for(int j=0;j<m;j++)
{
if(g[i][j]=='#')
{
a[k].x=i;a[k].y=j;a[k++].step=0;
}
}
}
int ans=INF;
//cout<<k<<endl;
for(int i=0;i<k;i++)
for(int j=0;j<k;j++)
{
memset(vis,0,sizeof(vis));
int L=BFS(a[i],a[j]);
//cout<<L<<endl;
if(L<ans&&fun())
{
ans=L;
}
}
if(ans==INF)
printf("Case %d: -1\n",c);
else
printf("Case %d: %d\n",c,ans);
}
return 0;
}