数据:
3
4 4
####
#JF#
#..#
#..#
3 3
FFF
FJF
FFF
3 3
...
.J.
...
嗯,被第三个数据卡啦半天....
两次BFS 预处理一下每个点最早着火的时间.
/* *********************************************** Author :pk29 Created Time :2015/8/19 19:26:13 File Name :4.cpp ************************************************ */ #include <iostream> #include <cstring> #include <cstdlib> #include <stdio.h> #include <algorithm> #include <vector> #include <queue> #include <set> #include <map> #include <string> #include <math.h> #include <stdlib.h> #include <iomanip> #include <list> #include <deque> #include <stack> #define ull unsigned long long #define ll long long #define mod 90001 #define INF 0x3f3f3f3f #define maxn 10000+10 #define cle(a) memset(a,0,sizeof(a)) const ull inf = 1LL << 61; const double eps=1e-5; using namespace std; struct node{ int x,y,dist; }; bool cmp(int a,int b){ return a>b; } int dir[4][2]={1,0,0,1,0,-1,-1,0}; char mp[1100][1100]; int vis[1100][1100],val[1100][1100]; int n,m,sx,sy,fx,fy; queue<node>p; void bfs1(){ cle(vis); node u,v; while(!p.empty()){ u=p.front(),p.pop(); for(int i=0;i<4;i++){ int nx=u.x+dir[i][0]; int ny=u.y+dir[i][1]; if(!vis[nx][ny]&&nx<=n&&ny>=1&&nx>=1&&ny<=m&&mp[nx][ny]=='.'){ v.x=nx,v.y=ny,v.dist=u.dist+1; vis[nx][ny]=1; val[nx][ny]=v.dist; p.push(v); } } } } queue<node>q; void bfs2(){ int mark=0; cle(vis); while(!q.empty())q.pop(); node u,v; u.x=sx,u.y=sy,u.dist=0; q.push(u); vis[u.x][u.y]=1; while(!q.empty()){ u=q.front(),q.pop(); if(u.x==n||u.x==1||u.y==1||u.y==m){ mark=1;printf("%d ",u.dist+1);break; } for(int i=0;i<4;i++){ int nx=u.x+dir[i][0]; int ny=u.y+dir[i][1]; if(vis[nx][ny]==0&&nx<=n&&ny>=1&&nx>=1&&ny<=m&&mp[nx][ny]=='.'){ v.dist=u.dist+1; if(v.dist<val[nx][ny]){ v.x=nx,v.y=ny; q.push(v); vis[nx][ny]=1; } } } } if(!mark)printf("IMPOSSIBLE "); } int main() { #ifndef ONLINE_JUDGE freopen("in.txt","r",stdin); #endif //freopen("out.txt","w",stdout); int t; cin>>t; while(t--){ cin>>n>>m; cle(mp); memset(val,INF,sizeof val); for(int i=1;i<=n;i++) for(int j=1;j<=m;j++){ cin>>mp[i][j]; if(mp[i][j]=='J'){ sx=i,sy=j; } if(mp[i][j]=='F'){ node o;o.x=i,o.y=j,o.dist=0; p.push(o); } } bfs1(); bfs2(); } return 0; }