UVA11624(bfs)

时间:2021-04-10 20:37:35

题意:给一张图,有火源,有障碍物,剩下的是道路,火源在下一分钟能够让上下左右四个方向的道路也着火,告诉人的位置,问最短时间能逃出去的时间是多少;

思路:一个bfs用来求出所有的火源能蔓延到的地方,另一个bfs求最短路,本来我以为bfs只能求最短路;

超级源:有多个源头的时候,就把所有的都压进去,每个源头能蔓延到的地方都看作是新的源头,继续压进去,每个只能蔓延4个方向,直到空;

 #include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <queue>
#include <algorithm>
#include <vector>
#include <cstring>
#include <stack>
#include <cctype>
#include <utility>
#include <map>
#include <string>
#include <climits>
#include <set>
#include <string>
#include <sstream>
#include <utility>
#include <ctime>
using namespace std;
const int MAXN();
const int MAXM();
int fire[MAXN][MAXN];
char g[MAXN][MAXN];
bool vis[MAXN][MAXN];
int fx[MAXM], fy[MAXM];
int R, C, SX, SY;
struct NODE
{
int x, y, val;
NODE()
{}
NODE(int tx, int ty, int td): x(tx), y(ty), val(td)
{}
}; int ok(int nx,int ny)
{
if(nx >= && nx <= R && ny >= && ny <= C )
return ;
return ;
}
int move_x[] = {, -, , };
int move_y[] = {-, , , }; void bfs1(int n)///多个起点,超级源
{
queue<NODE> q;
memset(fire+, -, sizeof(fire));
for(int i = ; i < n; ++i)///起点都压进去
{
q.push(NODE(fx[i], fy[i], ));
fire[fx[i]][fy[i]] = ;
}
NODE cur;
while(!q.empty())
{
cur = q.front();///从一个起点开始,然后四个方向扩散
q.pop();
for(int i = ; i < ; ++i)
{
int nx = cur.x+move_x[i], ny = cur.y+move_y[i];
if(ok(nx,ny)&& g[nx][ny] != '#' && fire[nx][ny] == -)
{
fire[nx][ny] = cur.val+;
q.push(NODE(nx, ny, cur.val+));
///重新做一个新的起点
}
}
}
} int bfs2()
{
queue<NODE> q;
memset(vis+, false, sizeof(vis[])*R);
q.push(NODE(SX, SY, ));
vis[SX][SY] = true;
NODE cur;
while(!q.empty())
{
cur = q.front();
q.pop();
if(cur.x == || cur.y == || cur.x == R || cur.y == C)
return cur.val+;
for(int i = ; i < ; ++i)
{
int nx = cur.x+move_x[i], ny = cur.y+move_y[i];
if(ok(nx,ny)&& g[nx][ny] != '#' && !vis[nx][ny] && (fire[nx][ny] == - || cur.val+ < fire[nx][ny]))
{
vis[nx][ny] = true;
q.push(NODE(nx, ny, cur.val+));
}
}
}
return -;
} int main()
{
int T;
scanf("%d", &T);
while(T--)
{
scanf("%d%d", &R, &C);
int count = ;
for(int i = ; i <= R; ++i)
{
scanf("%s", g[i]+);
for(int j = ; j <= C; ++j)
{
if(g[i][j] == 'J')
{
SX = i;
SY = j;
}
if(g[i][j] == 'F')
{
fx[count] = i;
fy[count++] = j;
}
}
}
bfs1(count);
int ans = bfs2();
if(ans == -)
printf("IMPOSSIBLE\n");
else
printf("%d\n", ans);
}
return ;
}