题目链接:点我啊╭(╯^╰)╮
题目大意:
r × c r×c r×c 的图, J J J代表人的起始地点, F F F代表火的起始地点,人每走一步,火势也会向周围的某一个方向蔓延一个点,问人逃离这张图所需要的最小步数?
解题思路:
双队列BFS,先预处理火势到达每个点的时间,然后将人到达这个点的时间与火达到这个点的时间作比较。
代码思路:
注意火的起点可能有多个,人逃离地图后步数要加 1 1 1
核心:还是要灵活的运用BFS,用两次队列来简化问题
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int dx[]= {1,-1,0,0};
int dy[]= {0,0,1,-1};
char mp[1005][1005];
int step[1005][1005];
bool vis[1005][1005];
int r, c, n;
struct point {
int x, y, s;
point() {}
point(int X, int Y, int S) {
x=X; y=Y; s=S;
}
} st, a;
void BFS() {
queue <point> q;
for(int i=1; i<=r; i++)
for(int j=1; j<=c; j++) {
step[i][j] = (1<<20);
if(mp[i][j]=='J') st=point(i, j, 0);
if(mp[i][j]=='F') {
q.push(point(i, j, 0));
step[i][j] = 0;
}
}
while(!q.empty()) {
a=q.front();
q.pop();
for(int i=0; i<4; i++) {
point n;
n.x=a.x+dx[i];
n.y=a.y+dy[i];
if(n.x>0 && n.x<=r && n.y>0 && n.y<=c && mp[n.x][n.y]!='#'\
&& (step[n.x][n.y]>(step[a.x][a.y]+1))) {
step[n.x][n.y] = step[a.x][a.y] + 1;
q.push(n);
}
}
}
q.push(st);
vis[st.x][st.y] = true;
while(!q.empty()) {
a=q.front();
q.pop();
for(int i=0; i<4; i++) {
point n;
n.x=a.x+dx[i];
n.y=a.y+dy[i];
if(n.x<1 || n.x>r || n.y<1 || n.y>c){
printf("%d\n", a.s+1);
return;
}
if(((a.s+1)<step[n.x][n.y]) && mp[n.x][n.y]!='#' && !vis[n.x][n.y]) {
n.s = a.s + 1;
vis[n.x][n.y] = true;
q.push(n);
}
}
}
printf("IMPOSSIBLE\n");
}
int main() {
scanf("%d", &n);
while(n--) {
memset(vis, 0, sizeof(vis));
scanf("%d%d", &r, &c);
for(int i=1; i<=r; i++)
scanf("%s", mp[i]+1);
BFS();
}
}