#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <cstring>
#include <queue>
using namespace std;
#define INF 11000000
const int maxn = 1110;
char maze[maxn][maxn];
int n,m,Time[maxn][maxn],vis[maxn][maxn],sx,sy,fx[maxn],fy[maxn],degf,dist[maxn][maxn];
struct node{
int x,y;
node(int x=0,int y=0):x(x),y(y){}
};
const int dx[]={0,1,0,-1};
const int dy[]={1,0,-1,0};
bool judge(int x,int y){
return x>=0&&x<n&&y>=0&&y<m;
}
void bfs_firetime(){
queue<node> q;
for(int i=0;i<degf;i++){
q.push(node(fx[i],fy[i]));
dist[fx[i]][fy[i]]=0;
}
while(!q.empty()){
node& u=q.front(); q.pop();
for(int d=0;d<4;d++){
int nx=dx[d]+u.x,ny=dy[d]+u.y;
if(judge(nx,ny)&&maze[nx][ny]!='#'){
if(dist[nx][ny]>dist[u.x][u.y]+1){
dist[nx][ny]=dist[u.x][u.y]+1;
q.push(node(nx,ny));
}
}
}
}
}
int bfs(){
memset(vis,0,sizeof(vis));
queue<node> q;
q.push(node(sx,sy));
Time[sx][sy]=0; vis[sx][sy]=1;
if(sx==0||sy==0||sx==n-1||sy==m-1) return 1;
while(!q.empty()){
node& u=q.front(); q.pop();
for(int d=0;d<4;d++){
int nx=dx[d]+u.x,ny=dy[d]+u.y;
if(judge(nx,ny)&&maze[nx][ny]!='#'&&!vis[nx][ny]){
if(dist[nx][ny]>Time[u.x][u.y]+1){
vis[nx][ny]=1;
Time[nx][ny]=Time[u.x][u.y]+1;
if(nx==0||ny==0||nx==n-1||ny==m-1) {
return Time[nx][ny]+1;
}
q.push(node(nx,ny));
}
}
}
}
return -1;
}
int main()
{
int T;
scanf("%d",&T);
while(T--){
scanf("%d %d",&n,&m);
degf=0;
for(int i=0;i<n;i++){
scanf("%s",maze[i]);
for(int j=0;j<m;j++){
if(maze[i][j]=='J'){sx=i; sy=j;}
if(maze[i][j]=='F'){fx[degf]=i; fy[degf++]=j;}
}
}
for(int i=0;i<=n;i++) for(int j=0;j<=m;j++) dist[i][j]=INF;
bfs_firetime();
int ans=bfs();
if(ans>0) printf("%d\n",ans);
else printf("IMPOSSIBLE\n");
}
return 0;
}
UVA - (单点BFS , 多源点同时加入queue)
最新推荐文章于 2024-05-02 15:08:51 发布