Title Link: http://uva.onlinejudge.org/external/116/11624.pdf
Test instructions: Given a maze and some ignition points, the fire will constantly want to spread around, seeking a shortest path to escape the maze.
Idea: First use BFS to find out the fire spread to each point of the shortest time, you can set the # time to 0, '. ' The fire can't be set to OO (it should be noted here, WA once). The following is the conventional BFS to find the shortest.
Code:
#include <iostream> #include <sstream> #include <cstdio> #include <cmath> #include <cstring
> #include <algorithm> #include <queue> #include <vector> #define LL Long long #define INF 0x7fffffff
using namespace Std;
struct node{int x,y,step;};
Char map[1010][1010];
int vis[1010][1010],dis[1010][1010];
int r,c,j[2];
Vector<int> F;
int d[][2]={1,0,-1,0,0,-1,0,1};
void BFs () {//Find out the time memset (vis,0,sizeof (VIS)) that the fire spreads to each point;
memset (dis,0,sizeof (dis));
Queue<node> Q;
for (int i=0;i< (int) f.size (); i++) Q.push ((node) {f[i]/r,f[i]%r,0}), vis[f[i]/r][f[i]%r]=1; while (!
Q.empty ()) {node Tp=q.front ();
Q.pop ();
for (int p=0;p<4;p++) {int tx=tp.x+d[p][0],ty=tp.y+d[p][1];
if (tx<0 | | ty<0 | | tx>=r | | ty>=c) continue;
if (map[tx][ty]!= '. ' | | vis[tx][ty]) continue;
dis[tx][ty]=tp.step+1;
Q.push (node) {tx,ty,tp.step+1}); Vis[tx][ty]=1; }} for (int i=0;i<r;i++) for (int j=0;j<c;j++)//The point where the fire is not spread and is the pass path, the time is set to Oo if (map[i][j]== '. ' &&!vi
S[I][J]) Dis[i][j]=inf;
} void BFs () {//Is now the conventional BFS for the shortest-circuited memset (vis,0,sizeof (VIS));
Queue<node> Q;
Q.push (node) {j[0],j[1],0});
Vis[j[0]][j[1]]=1; while (!
Q.empty ()) {node Tp=q.front ();
if (tp.x==0 | | tp.y==0 | | tp.x==r-1 | | tp.y==c-1) {cout<<tp.step+1<<endl;return;}
Q.pop ();
for (int p=0;p<4;p++) {int tx=tp.x+d[p][0],ty=tp.y+d[p][1];
if (tx<0 | | ty<0 | | tx>=r | | ty>=c) continue;
if (Vis[tx][ty] | | tp.step+1>=dis[tx][ty]) continue;
Vis[tx][ty]=1;
Q.push (node) {tx,ty,tp.step+1});
}} cout<< "impossible\n";
} int main () {//freopen ("D:\\in.txt", "R", stdin);
int t;cin>>t; while (t--) {cin>>r>>c;
F.clear ();
GetChar (); for (int i=0;i&lT
r;i++) {for (int j=0;j<c;j++) {scanf ("%c", &map[i][j]);
if (map[i][j]== ' J ') j[0]=i,j[1]=j;
else if (map[i][j]== ' F ') f.push_back (I*R+J);
} getchar ();
} BFS ();
BFS ();
} return 0;
}