原题链接:https://www.acwing.com/problem/content/description/4226/
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
const int N=15,INF=0x3f3f3f3f;
#define x first
#define y second
int n,m;
typedef pair<int,int> PII;
char g[N][N];
int cnt,ans;
int dist[N][N];
int dx[4]={1,-1,0,0},dy[4]={0,0,1,-1};
void bfs(PII a,PII b)
{
queue<PII> q;
q.push(a);
q.push(b);
int num=2;
memset(dist,0x3f,sizeof dist);
dist[a.x][a.y]=0,dist[b.x][b.y]=0;
int res=0;
while(q.size())
{
PII t=q.front();
q.pop();
if(num==cnt){
ans=min(res,ans);
return;
}
for(int i=0;i<4;i++)
{
int x=dx[i]+t.x,y=dy[i]+t.y;
if(x<0||x>=n||y<0||y>=m||g[x][y]=='.') continue;
if(dist[x][y]==INF){
dist[x][y]=dist[t.x][t.y]+1;
num++;
res=max(dist[x][y],res);
q.push({x,y});
}
}
}
}
int main()
{
int tt;
cin>>tt;
for(int c=1;c<=tt;c++)
{
cin>>n>>m;
vector<PII> nums;
cnt=0,ans=INF;
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
{
cin>>g[i][j];
if(g[i][j]=='#'){
nums.push_back({i,j});
cnt++;
}
}
if(cnt<=2) ans=0;
if(cnt==0) ans=-1;
int len=nums.size();
for(int i=0;i<len;i++)
for(int j=0;j<i;j++)
{
bfs(nums[i],nums[j]);
}
if(ans==INF) ans=-1;
printf("Case %d: %d\n",c,ans);
}
}
标签:PII,点火,dist,游戏,int,res,cnt,ans
From: https://www.cnblogs.com/linearlearn/p/17280828.html