例题为UVA-11624
本题中出现了类似动态地图的变量火焰,这时我们需要知道不同变量到达相同位置的时间关系,所以本题需要两次bfs并对时间信息进行记录,所以采用如下代码。
#include<iostream>
#include<stdio.h>
#include<vector>
#include<map>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<set>
#include<queue>
#include<cmath>
#define INF 0x3f3f3f3f
using namespace std;
const int N = 1005;
int dir[4][2] = {{-1,0},{0,1},{1,0},{0,-1}};
int n,m;
int st_x,st_y;
bool vis[N][N];
int times[N][N];
int step[N][N];
char a[N][N];
struct P{
int x,y,s;
P(){}
P(int px,int py,int ps):x(px),y(py),s(ps){}
};
queue<P> q;
bool check(int x, int y){
if(x < 0 || x >= n || y < 0 || y >= m)
return false;
if(vis[x][y])
return false;
return a[x][y] == '.';
}
void clear_q(){
while(!q.empty())
q.pop();
}
void bfs_time(){
while(!q.empty()){
P cur = q.front();
q.pop();
for(int i = 0; i < 4; ++i){
int nx = cur.x + dir[i][0];
int ny = cur.y + dir[i][1];
if(check(nx,ny)){
vis[nx][ny] = true;
times[nx][ny] = times[cur.x][cur.y] + 1;
q.push(P(nx,ny,times[nx][ny]));
}
}
}
}
int bfs(int x, int y){
step[x][y] = 0;
q.push(P(x,y,0));
vis[x][y] = true;
while(!q.empty()){
P cur = q.front();
q.pop();
if(cur.x == 0 || cur.x == n-1 || cur.y == 0 || cur.y == m-1){
return step[cur.x][cur.y] + 1;
}
for(int i = 0; i < 4; ++i){
int nx = cur.x + dir[i][0];
int ny = cur.y + dir[i][1];
if(check(nx,ny) && step[cur.x][cur.y] + 1 < times[nx][ny]){
step[nx][ny] = step[cur.x][cur.y] + 1;
vis[nx][ny] = true;
q.push(P(nx,ny,step[nx][ny]));
}
}
}
return -1;
}
int main()
{
ios::sync_with_stdio(false);
int t;
cin >> t;
while(t--){
cin >> n >> m;
memset(times,INF,sizeof(times));
memset(vis,false,sizeof(vis));
for(int i = 0; i < n; ++i){
for(int j = 0; j < m; ++j){
cin >> a[i][j];
if(a[i][j] == 'J'){
st_x = i;
st_y = j;
}
if(a[i][j] == 'F'){
vis[i][j] = true;
q.push(P(i,j,0));
times[i][j] = 0;
}
}
}
bfs_time();
clear_q();
memset(vis,false,sizeof(vis));
int ans = bfs(st_x,st_y);
if(ans == -1){
cout << "IMPOSSIBLE" <<endl;
}
else{
cout << ans << endl;
}
}
return 0;
}
代码借用
作者:Tianweidadada
来源:CSDN
原文:https://blog.csdn.net/tianweidadada/article/details/81985207
版权声明:本文为博主原创文章,转载请附上博文链接!