标签:uva
Given Joe‘s location in the maze and which squares of the maze are on fire, you must determine whether Joe can exit the maze before the fire reaches him, and how fast he can do it.
Joe and the fire each move one square per minute, vertically or horizontally (not diagonally). The fire spreads all four directions from each square that is on fire. Joe may exit the maze from any square that borders the edge of the maze. Neither Joe nor the fire may enter a square that is occupied by a wall.
2 4 4 #### #JF# #..# #..# 3 3 ### #J. #.F
3 IMPOSSIBLE
题目大意:一个平面迷宫中有一个人,迷宫中有些点起火了,火和人每个单位时间只能向相邻的格子移动,其中有一些空间被墙壁占据,问这个人在不背或烧到的情况下,离开迷宫的最快时间。
题解:两次bfs,先bfs出每个地方着火的时间,再bfs人走出迷宫的时间。注意有的地方火不能到达但人是可以走的。
/** * @author neko01 */ //#pragma comment(linker, "/STACK:102400000,102400000") #include <cstdio> #include <cstring> #include <string.h> #include <iostream> #include <algorithm> #include <queue> #include <vector> #include <cmath> #include <set> #include <map> using namespace std; typedef long long LL; #define min3(a,b,c) min(a,min(b,c)) #define max3(a,b,c) max(a,max(b,c)) #define pb push_back #define mp(a,b) make_pair(a,b) #define clr(a) memset(a,0,sizeof a) #define clr1(a) memset(a,-1,sizeof a) #define dbg(a) printf("%d\n",a) typedef pair<int,int> pp; const double eps=1e-9; const double pi=acos(-1.0); const int INF=0x3f3f3f3f; const LL inf=(((LL)1)<<61)+5; const int N=1005; int f[N][N]; bool vis[N][N]; char s[N][N]; int r,c,sx,sy; struct node{ int x,y,t; node(int x=0,int y=0,int t=0):x(x),y(y),t(t){} }; int dir[4][2]={-1,0,1,0,0,-1,0,1}; bool immap(int x,int y) { return x>=0&&y>=0&&x<r&&y<c&&!vis[x][y]&&s[x][y]!='#'; } int bfs() { queue<node>q; clr(vis); q.push(node(sx,sy,0)); vis[sx][sy]=true; while(!q.empty()) { node cur=q.front(); int x=cur.x,y=cur.y; if(x==0||y==0||x==r-1||y==c-1) return cur.t+1; q.pop(); for(int i=0;i<4;i++) { int xx=x+dir[i][0]; int yy=y+dir[i][1]; if(immap(xx,yy)) { if(cur.t+1<f[xx][yy]||f[xx][yy]==-1) { vis[xx][yy]=true; q.push(node(xx,yy,cur.t+1)); } } } } return -1; } int main() { int t; scanf("%d",&t); while(t--) { queue<node>q; scanf("%d%d",&r,&c); clr1(f); for(int i=0;i<r;i++) { scanf("%s",s[i]); for(int j=0;j<c;j++) { vis[i][j]=false; if(s[i][j]=='J') sx=i,sy=j; if(s[i][j]=='F') { f[i][j]=0; q.push(node(i,j,0)); vis[i][j]=true; } } } while(!q.empty()) { node cur=q.front(); int x=cur.x,y=cur.y; q.pop(); for(int i=0;i<4;i++) { int xx=x+dir[i][0]; int yy=y+dir[i][1]; if(immap(xx,yy)) { f[xx][yy]=f[x][y]+1; q.push(node(xx,yy,cur.t+1)); vis[xx][yy]=true; } } } int ans=bfs(); if(ans==-1) puts("IMPOSSIBLE"); else printf("%d\n",ans); } return 0; }
标签:uva
原文地址:http://blog.csdn.net/neko01/article/details/40322749