标签:
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
#include <iostream> #include <cstdio> #include <cstring> #include <queue> using namespace std; #define INF 1<<30 #define N 1010 struct JF { int x,y,t; JF(){} JF(int x,int y,int t):x(x),y(y),t(t){} }; int n,m; int jx,jy; queue<JF> q; int vis[N][N]; int fire[N][N]; //fire[i][j]表示火到i,j位置的最短时间 char mpt[N][N]; int dir[4][2]={1,0,-1,0,0,1,0,-1}; bool judge(int x,int y) { if(x<1 || x>n || y<1 || y>m) return 0; if(mpt[x][y]==‘#‘) return 0; return 1; } void bfs1() { JF now,next; while(!q.empty()) { now=q.front(); q.pop(); for(int i=0;i<4;i++) { next=now; next.t++; next.x+=dir[i][0]; next.y+=dir[i][1]; if(judge(next.x,next.y)) { if(next.t<fire[next.x][next.y]) { fire[next.x][next.y]=next.t; q.push(next); } } } } } void bfs2() { queue<JF> q; memset(vis,0,sizeof(vis)); JF now,next; now.x=jx; now.y=jy; now.t=0; vis[jx][jy]=1; q.push(now); while(!q.empty()) { now=q.front(); q.pop(); if(now.x==1 || now.x==n || now.y==1 || now.y==m) { cout<<now.t+1<<endl; return; } for(int i=0;i<4;i++) { next=now; next.t++; next.x+=dir[i][0]; next.y+=dir[i][1]; if(judge(next.x,next.y) && !vis[next.x][next.y] && fire[next.x][next.y]-next.t>=1) { vis[next.x][next.y]=1; q.push(next); } } } cout<<"IMPOSSIBLE\n"; } int main() { int T; scanf("%d",&T); while(T--) { scanf("%d%d",&n,&m); for(int i=1;i<=n;i++) { scanf("%s",mpt[i]+1); } for(int i=1;i<=n;i++) { for(int j=1;j<=m;j++) { fire[i][j]=INF; if(mpt[i][j]==‘F‘) { fire[i][j]=0; q.push(JF(i,j,0)); } else if(mpt[i][j]==‘J‘) { jx=i; jy=j; } } } bfs1(); bfs2(); } return 0; }
标签:
原文地址:http://www.cnblogs.com/hate13/p/4175394.html