UVa 11624 (BFS) Fire!

也是一个走迷宫的问题,不过又有了点变化。

这里迷宫里有若干把火,而且火每秒也是向四个方向蔓延的。问人是否能走出迷宫。

我用了两遍BFS,第一遍把所有着火的格子加入队列,然后计算每个格子着火的时间。

第二遍便是走迷宫,只有当这个格子不是墙,而且当前时间在这个格子着火之前才能拓展。当然,并不是所有的空格都一定会着火。

 #include <cstdio>
#include <cstring>
#include <queue>
using namespace std; struct Node
{
int x, y, t;
Node(int x=, int y=, int t=):x(x), y(y), t(t) {}
}; Node st; const int maxn = + ;
int row, col;
char maze[maxn][maxn];
int time[maxn][maxn];
bool vis[maxn][maxn]; int dx[] = { , , , - };
int dy[] = { , , -, }; inline bool in(int x, int y)
{ return x >= && x < row && y >= && y < col; } inline bool border(int x, int y)
{ return x == || x == row- || y == || y == col-; } void init()
{
memset(time, -, sizeof(time));
queue<Node> Q;
for(int i = ; i < row; i++)
for(int j = ; j < col; j++)
{
if(maze[i][j] == 'F') { Q.push(Node(i, j, )); time[i][j] = ; }
if(maze[i][j] == 'J') { st.x = i; st.y = j; st.t = ; }
}
while(!Q.empty())
{
Node now = Q.front(); Q.pop();
for(int i = ; i < ; i++)
{
int x = now.x + dx[i];
int y = now.y + dy[i];
int t = now.t + ;
if(in(x, y) && time[x][y] < && maze[x][y] != '#')
{
Q.push(Node(x, y, now.t + ));
time[x][y] = t;
}
}
}
} int BFS()
{
memset(vis, false, sizeof(vis));
queue<Node> Q;
Q.push(st);
vis[st.x][st.y] = true;
while(!Q.empty())
{
Node now = Q.front(); Q.pop();
if(border(now.x, now.y)) return now.t + ;
for(int i = ; i < ; i++)
{
int x = now.x + dx[i];
int y = now.y + dy[i];
int t = now.t + ;
if(in(x, y) && !vis[x][y] && maze[x][y] != '#')
{
if(time[x][y] >= && time[x][y] <= t) continue;
vis[x][y] = true;
Q.push(Node(x, y, t));
}
}
}
return ;
} int main()
{
//freopen("in.txt", "r", stdin); int T; scanf("%d", &T);
while(T--)
{
scanf("%d%d", &row, &col);
for(int i = ; i < row; i++) scanf("%s", maze[i]);
init();
int ans = BFS();
if(ans) printf("%d\n", ans);
else puts("IMPOSSIBLE");
} return ;
}

代码君

上一篇:[转]Windows Shell 编程 第四章 【来源 http://blog.csdn.net/wangqiulin123456/article/details/7987933】


下一篇:Jquery Mobile左右滑动效果