# UVA11624Fire!(BFS)

```#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;
const int INF = 0x3f3f3f3f;
const int Max = 1000 + 10;
int fire[Max][Max],g[Max][Max],vis[Max][Max];
int R,C;
int sx, sy;
int gx[4] = {0, 0, 1, -1};
int gy[4] = {-1, 1, 0, 0};
int Time;
struct Node
{
int x,y;
};
queue<Node> Fire;
void solve(int i, int j, char ch)
{
if(ch == '#')
{
g[i][j] = -1;
vis[i][j] = INF;
fire[i][j] = INF;
}
else if(ch == '.')
{
g[i][j] = 1;
vis[i][j] = INF;
fire[i][j] = INF;
}
else if(ch == 'J')
{
sx = i;
sy = j;
vis[i][j] = 0;
fire[i][j] = INF;
}
else if(ch == 'F')
{
fire[i][j] = 0;
vis[i][j] = INF;
g[i][j] = 0;
Node node;
node.x = i;
node.y = j;
Fire.push(node);
}
}
void fire_bfs()  // 对大火蔓延的bfs
{
while(!Fire.empty())
{
Node node = Fire.front();
Fire.pop();
for(int i = 0; i < 4; i++)
{
int fx = node.x + gx[i];
int fy = node.y + gy[i];
if(fx >= 1 && fx <= R && fy >= 1 && fy <= C && g[fx][fy] != -1)
{
if(fire[fx][fy] > fire[node.x][node.y] + 1)
{
fire[fx][fy] = fire[node.x][node.y] + 1;
Node temp;
temp.x = fx;
temp.y = fy;
Fire.push(temp);
}
}
}
}
}
{
Node node;
node.x = sx;
node.y = sy;
{
if(node.x == 1 || node.x == R || node.y == 1 || node.y == C)
{
Time = vis[node.x][node.y];
return;
}
for(int i = 0; i < 4; i++)
{
int fx = node.x + gx[i];
int fy = node.y + gy[i];
if(fx >= 1 && fy >= 1 && fx <= R && fy <= C && g[fx][fy] != -1)
{
if(vis[fx][fy] > vis[node.x][node.y] + 1 && vis[node.x][node.y] + 1 < fire[fx][fy])
{
vis[fx][fy] = vis[node.x][node.y] + 1;
Node temp;
temp.x = fx;
temp.y = fy;
}
}
}
}
}
int main(int argc, char** argv)
{
int test;
scanf("%d", &test);
while (test--)
{
while(!Fire.empty())
Fire.pop();
scanf("%d%d", &R, &C);
getchar();
char ch;
for(int i = 1; i <= R; i++)
{
for(int j = 1; j <= C; j++)
{
scanf("%c", &ch);
solve(i, j, ch);
}
getchar();
}
Time = INF;
fire_bfs();
if(Time != INF)
printf("%d\n", Time + 1);
else
printf("IMPOSSIBLE\n");

}
return 0;
}```

原文作者：zhaop
原文地址: https://www.cnblogs.com/zhaopAC/p/5265243.html
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。