在一个迷宫中,有一个人J和一些火苗(用F表示,数量很多),人和火苗同时移动,问人在不触碰火苗燃烧地方的情况下,能不能出去,及不与火苗走的路径相交。
本题一共两种解法,我们知道人和火苗的路径是不能确定的,而求某一种东西的最短时间一般用BFS,两种状态同时转换,怎么办呢?
第一种方法,进行两边BFS,第一遍记录火苗的路径,并存储火苗到每一个点的最短时间,第二遍bfs走人,每一步的时间要小于火苗蔓延到的时间才可以通过。两边BFS即可得出结果。但是有些复杂
第二种办法,只需要进行一遍BFS,火苗走过的人不能走,那我们可以把火苗走过的地方假设成为墙,这样的话让火苗先走,人再跟着走,人在走的时候进行判断,不能走走过的,不能走墙,不能走出边界,这样的话会简单很多。下面给出第二种方法的代码。
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;
int T, n, m, ans;
char M[1005][1005];
int used[1005][1005];
int cx[4] = {0, 0, -1, 1},
cy[4] = {1, -1, 0, 0};
struct l{
int x, y;
int step;
int flag;
}f, s;
queue<l> q;
bool check(int x, int y) {
if(x >= 0 && x < n && y >= 0 && y < m && !used[x][y] && M[x][y] != '#')
return true;
return false;
}
void BFS()
{
while(!q.empty()) {
f = q.front();
q.pop();
if(!f.flag && (f.x == 0 || f.x == n - 1 || f.y == 0 || f.y == m - 1)) {
ans = f.step;
break;
}
for(int i = 0; i < 4; i++) {
s.x = f.x + cx[i];
s.y = f.y + cy[i];
s.step = f.step + 1;
s.flag = f.flag;
if(check(s.x, s.y)) {
used[s.x][s.y] = 1;
q.push(s);
}
}
}
}
int main()
{
cin >> T;
while(T--) {
ans = -1;
memset(used, 0, sizeof(used));
cin >> n >> m;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
cin >> M[i][j];
if(M[i][j] == 'J') {
f.x = i;
f.y = j;
f.step = 0;
f.flag = 0;
used[i][j] = 1;
}
if(M[i][j] == 'F') {
s.x = i;
s.y = j;
s.step = 0;
s.flag = 1;
q.push(s);
used[i][j] = 1;
}
}
}
q.push(f);
BFS();
while(!q.empty())
q.pop();
if(ans != -1)
cout << ans + 1 << endl;
else
cout << "IMPOSSIBLE" << endl;
}
return 0;
}