11624 Fire! bfs
阿新 • • 發佈:2018-12-20
題意:有一個迷宮,迷宮裡有多個火堆和一個人,每一分鐘人可以移動一個單元格,同時每堆火焰可以同時向上下左右四個方向移動,每分鐘火堆先移動,且人不能移動到有火堆的單元格,求人能否逃離迷宮且若能逃離則最短用時是多少。
思路:典型的bfs,由於火堆和人都要擴充套件,且火堆每分鐘要比人先移動,則初始化時,我們可以先把火堆放入佇列中再放入人,這樣每分鐘總能先擴充套件完所有火堆的移動,再擴充套件人的移動。之後就是模板題了。
#include<cstdio> #include<iostream> #include<algorithm> #include<cmath> #include<cstring> #include<string> #include<map> #include<vector> #include<queue> #include<deque> using namespace std; #define ll long long #define PI acos(-1) #define INF 0x3f3f3f3f #define NUM 33010 #define debug true #define lowbit(x) ((-x)&x) #define ffor(i,d,u) for(int i=(d);i<=(u);++i) #define _ffor(i,u,d) for(int i=(u);i>=(d);--i) #define mst(array,Num,Kind,Count) memset(array,Num,sizeof(Kind)*(Count)) const int P = 1e9+7; int T; int n,m; char ma[1005][1005]; int check[1005][1005]; int h[4]={0,0,1,-1},l[4]={-1,1,0,0}; struct node { int flag; int posx,posy; int step; }; queue < node > q; template <typename T> void read(T& x) { x=0; char c;T t=1; while(((c=getchar())<'0'||c>'9')&&c!='-'); if(c=='-'){t=-1;c=getchar();} do(x*=10)+=(c-'0');while((c=getchar())>='0'&&c<='9'); x*=t; } template <typename T> void write(T x) { int len=0;char c[21]; if(x<0)putchar('-'),x*=(-1); do{++len;c[len]=(x%10)+'0';}while(x/=10); _ffor(i,len,1)putchar(c[i]); } inline bool bfs() { node t1,t2; int x,y; while(!q.empty()) { t1 = q.front(),q.pop(); if(t1.flag == 2&&(t1.posx == 1||t1.posx == n||t1.posy == 1||t1.posy == m)) { write(t1.step+1); putchar('\n'); return false; } t2 = t1; ++t2.step; ffor(i,0,3) { x = t1.posx+h[i],y = t1.posy+l[i]; if(x < 1||x > n||y < 1||y > m||ma[x][y] == '#')continue; if(t1.flag == 1&&check[x][y] != 1) { check[x][y] = 1; t2.posx = x,t2.posy = y; q.push(t2); } if(t1.flag == 2&&check[x][y] != 1&&check[x][y] !=2) { check[x][y] = 2; t2.posx = x,t2.posy = y; q.push(t2); } } } return true; } void AC() { node x; read(T); int pos1,pos2; while(T--) { read(n),read(m); x.step = 0; x.flag = 1; while(!q.empty())q.pop(); ffor(i,1,n) { ffor(j,1,m) { ma[i][j] = getchar(); check[i][j] = 0; if(ma[i][j] == 'F') { x.posx = i,x.posy = j; check[i][j] = 1; q.push(x); } if(ma[i][j] == 'J')pos1 = i,pos2 = j,check[i][j] = 2; } getchar(); } x.posx = pos1,x.posy = pos2; x.flag = 2; q.push(x); if(bfs())puts("IMPOSSIBLE"); } } int main() { AC(); return 0; }