bfs,稍複雜的bfs,將火和人的位置分別bfs(先火再人),直到人到達邊界或是被火圍住無路可走時結束。
代碼如下:
#include <cstdio>#include <cstring>const int MAXN = 1001;struct point{ int x, y, mem_step; bool bool_fire;// 區分是否是‘火’} que[MAXN*MAXN];int r, c, fx, fy;int step_x[4]= {1,-1,0,0};int step_y[4]= {0,0,1,-1};char image[MAXN][MAXN];bool vis[MAXN][MAXN];int bfs(){ int font=0, rear=0; memset(vis, false, sizeof(vis)); for(int i=0; i<r; i++) for(int j=0; j<c; j++)// '火'進隊列(注意:初始時不止一個位置‘起火’) if(image[i][j]=='F') { que[rear].x = j; que[rear].y = i; que[rear].mem_step = 0; que[rear].bool_fire = true; ++rear; } que[rear].x=fx;// '人'進隊列 que[rear].y=fy; que[rear].mem_step = 0; que[rear++].bool_fire = false; while(font<rear) { int xx = que[font].x; int yy = que[font].y; if(que[font].bool_fire)// 對‘火’進行擴充 { for(int i=0; i<4; i++) { xx = que[font].x + step_x[i]; yy = que[font].y + step_y[i]; if(xx<0||xx>=c||yy<0||yy>=r||image[yy][xx]=='#'||image[yy][xx]=='F') continue; image[yy][xx] = 'F'; que[rear].x = xx; que[rear].y = yy; que[rear].bool_fire = true; que[rear].mem_step = que[font].mem_step+1; ++rear; } } else { for(int i=0; i<4; i++)// 對‘人’進行擴充 { int xx = que[font].x + step_x[i]; int yy = que[font].y + step_y[i]; if(vis[yy][xx]||image[yy][xx]=='#'||image[yy][xx]=='F') continue; if(xx<0||xx>=c||yy<0||yy>=r) return que[font].mem_step+1; vis[yy][xx] = true; que[rear].x = xx; que[rear].y = yy; que[rear].bool_fire = false; que[rear].mem_step = que[font].mem_step+1; ++rear; } } ++font; } return 0;}int main(){#ifdef test freopen("sample.txt", "r", stdin);#endif int t, flag; scanf("%d", &t); while(t--) { scanf("%d%d", &r, &c); fx = fy = -1; for(int i=0; i<r; i++) { scanf("%s", image[i]); if(fx == -1) for(int j=0; j<c; j++) if(image[i][j] == 'J') { fx = j; fy = i; break; } } flag = bfs(); if(flag) printf("%d\n", flag); else printf("IMPOSSIBLE\n"); } return 0;}