https://vjudge.net/problem/UVA-11624
题意: 一个迷宫里,有若干处火种(没看清题,WA到死),每过一秒,火向四个方向烧过去。人每一秒可以走一步,走到边界就算逃生成功。 求逃生 最短时间,不能逃生就输出impossible。
分析: 需要做两次bfs,注意先后顺序,先让火走,然后再让人走。用一个队列就可以。 bfs或者dfs最好写到一个函数里面,这样得到答案后可以直接return
#include<iostream>
#include<cstdio>
#include<string.h>
#include<math.h>
#include<string>
#include<map>
#include<set>
#include<vector>
#include<algorithm>
#include<queue>
#include<iomanip>
using namespace std;
const int INF = 0x3f3f3f3f;
const int NINF = 0xc0c0c0c0;
typedef long long ll;
char maze[1005][1005];
bool vis[1005][1005];
int jx,jy;
int fx[2000],fy[2000];
int dx[4] = {0,1,0,-1};
int dy[4] = {1,0,-1,0};
int n,m,k;
struct Point{
int x, y;
int step;
int t;
Point(int step=0):step(step) {} ;
};
bool bfs(int jx,int jy){
Point beg;
beg.x = jx;
beg.y = jy;
beg.t = 1;
queue<Point> q;
for(int i=0;i<k;i++){
Point temp;
temp.x = fx[i];
temp.y = fy[i];
temp.t = 2;
q.push(temp);
}
q.push(beg);
int flag = 0;
while(!q.empty()){
Point temp = q.front();
q.pop();
if(temp.t == 2){
for(int i=0;i<4;i++){
Point dfire = temp;
dfire.x += dx[i];
dfire.y += dy[i];
dfire.step++;
if(dfire.x>=0 && dfire.x<m && dfire.y>=0 && dfire.y <n && vis[dfire.y][dfire.x] == 1){
q.push(dfire);
vis[dfire.y][dfire.x] = 0;
}
}
}
//printmaze();
else {
if(temp.x == 0 || temp.x == m-1 || temp.y == 0 || temp.y == n-1){
cout << temp.step+1 << endl;
return 0;
}
for(int i=0;i<4;i++){
Point dtemp = temp;
dtemp.x += dx[i];
dtemp.y += dy[i];
dtemp.step++;
if(dtemp.x >= 0 && dtemp.x <m && dtemp.y >= 0 && dtemp.y < n && vis[dtemp.y][dtemp.x] == 1){
q.push(dtemp);
vis[dtemp.y][dtemp.x] = 0;
}
}
}
}
return 1;
}
int main()
{
int T;
cin >> T;
while(T--){
cin >> n >> m;
memset(vis,0,sizeof(vis[0][0])*1005*1005);
k = 0;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
cin >> maze[i][j];
if(maze[i][j] == '.') vis[i][j] = 1;
if(maze[i][j] == 'J'){
jx = j;
jy = i;
}
if(maze[i][j] == 'F'){
fx[k] = j;
fy[k] = i;
k++;
}
}
}
if(bfs(jx,jy)) cout << "IMPOSSIBLE" << endl;
}
}