题目链接:https://cn.vjudge.net/problem/UVA-11624
题意:
人和火每分钟移动一个方格,上、下、左、右,四个方向中的一个。火势向四个方向同时蔓延。人可以从迷宫的任何一个边界逃离迷宫。无论是人还是火都不会到达有墙的位置。
题中说到人只有一个,火有很多,所以无法用正常的搜索来写。因为要判断人走出去的边界,和火的边界无法进行同时入队,所以我们对火进行预处理,让火先跑一个BFS,记录一下每个位置火到达的时间,然后在人进行BFS时判断一下火的时间,来进行搜索即可。
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<map>
#include<queue>
using namespace std;
inline void fast() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
}
typedef long long ll;
const double PI = acos(-1.0);
const double eps = 1e-6;
const int INF = 0x3f3f3f3f;
const int maxn = 1e3+10;
const int mod = 1000;
int n,m,T,sx,sy;
int Next[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};
int vis[maxn][maxn],timefire[maxn][maxn]; //标记数组,火到达的时间
char Map[maxn][maxn];
struct Node{
int x,y,step;
}NOW,NEXT;
queue<pair<int,int> > Q;
void bfs_fire(){ //对火进行预处理
while(!Q.empty()){
int xx = Q.front().first;
int yy = Q.front().second;
Q.pop();
for(int i = 0;i < 4;i++){
int dx = xx + Next[i][0];
int dy = yy + Next[i][1];
if(dx < 0 || dy < 0 || dx >= n || dy >= m)
continue;
if(Map[dx][dy] == '#' || vis[dx][dy])
continue;
vis[dx][dy] = 1;
timefire[dx][dy] = timefire[xx][yy] + 1;
Q.push(make_pair(dx,dy));
}
}
}
void bfs(){
memset(vis,0,sizeof(vis));
queue<Node> q;
NOW.x = sx; NOW.y = sy; NOW.step = 0;
vis[sx][sy] = 1;
q.push(NOW);
while(!q.empty()){
NOW = q.front(); q.pop();
for(int i = 0;i < 4;i++){
NEXT.x = NOW.x + Next[i][0];
NEXT.y = NOW.y + Next[i][1];
if(NEXT.x < 0 || NEXT.y < 0 || NEXT.x >= n || NEXT.y >= m){
cout << NOW.step + 1 << endl;
return ;
}
if(vis[NEXT.x][NEXT.y] || Map[NEXT.x][NEXT.y] == '#' || NOW.step + 1 >= timefire[NEXT.x][NEXT.y])
continue;
NEXT.step = NOW.step + 1;
vis[NEXT.x][NEXT.y] = 1;
q.push(NEXT);
}
}
cout << "IMPOSSIBLE" << endl;
}
int main() {
//freopen("C:\\Users\\nEo.大魔王\\Desktop\\12.txt","w",stdout);
cin >> T;
while(T--){
memset(timefire,INF,sizeof(timefire));
memset(vis,0,sizeof(vis));
cin >> n >> m;
for(int i = 0;i < n;i++){
for(int j = 0;j < m;j++){
cin >> Map[i][j];
if(Map[i][j] == 'J')
sx = i,sy = j;
else if(Map[i][j] == 'F'){
Q.push(make_pair(i,j));
vis[i][j] = 1;
timefire[i][j] = 0;
}
}
}
bfs_fire();
bfs();
}
return 0;
}