大同小异的bfs,同时把两个点压进队列就行了
做题真的要注意细节,不然wa到怀疑人生
https://vjudge.net/problem/FZU-2150
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<set>
#include<map>
#include<queue>
#include<cmath>
#define ll long long
#define mod 1000000007
#define inf 0x3f3f3f3f
using namespace std;
char a[15][15];
bool vis[15][15];
int dir[4][2] = {0, 1, 0, -1, 1, 0, -1, 0};
int n, m;
int cnt1;
struct node
{
int x, y, t;
}k[105];
int bfs(int x, int y, int x1, int y1)
{
vis[x1][y1] = 1;
vis[x][y] = 1;
if(x == x1 && y == y1) cnt1 += 1;
else cnt1 += 2;
queue<node> q;
node h, h1, next;
h.x = x, h.y = y, h.t = 0;
h1.x = x1, h1.y = y1, h1.t = 0;
q.push(h);
q.push(h1);
int maxy = 0;
while(! q.empty())
{
h = q.front();
q.pop();
for(int i = 0; i < 4; i ++)
{
int u = h.x + dir[i][0], v = h.y + dir[i][1];
if(! vis[u][v] && u <= n && v >= 1 && u >= 1 && v <= m && a[u][v] == '#')
{
vis[u][v] = 1;
cnt1 ++;
next.t = h.t + 1;
next.x = u, next.y = v;
q.push(next);
maxy = max(maxy, next.t);
}
}
}
return maxy;
}
int main()
{
int t;
scanf("%d", &t);
int cas = 0;
while(t --)
{
int miny = inf;
int cnt = 0;
scanf("%d%d", &n, &m);
for(int i = 1; i <= n; i ++)
{
for(int j = 1; j <= m; j ++)
{
cin>>a[i][j];
if(a[i][j] == '#')
{
k[++cnt].x = i;
k[cnt].y = j;
}
}
}
bool flag = 0;
int ans;
for(int i = 1; i <= cnt; i ++)
{
for(int j = i; j <= cnt; j ++)
{
cnt1 = 0;
memset(vis, 0, sizeof(vis));
ans = bfs(k[i].x, k[i].y, k[j].x, k[j].y);
if(cnt1 == cnt)
{
flag = 1;
miny = min(miny, ans);
}
}
}
if(flag)
printf("Case %d: %d\n",++cas, miny);
else printf("Case %d: -1\n", ++ cas);
}
return 0;
}