题目:
http://acm.hust.edu.cn/vjudge/contest/view.action?cid=72192#problem/A
思路:
先初始化每个格子火燃烧的时间,使用BFS.再BFS人走的时间.
注意火的燃烧点不只一个.
处理火的燃烧时间不可以用DFS,会爆栈.
AC.
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;
const int maxn = 1015;
int T, r, c;
char maze[maxn][maxn];
int vis[maxn][maxn], v[maxn][maxn];
int dx[] = {0, 0, 1, -1}, dy[] = {1, -1, 0, 0};
struct fire { int x, y; };
queue<fire> q;
bool yes(int xx, int yy)
{
if(xx < 0 || yy < 0 || xx >= r || yy >= c ||
maze[xx][yy] == '#')
return false;
return true;
}
bool ended(int a, int b)
{
if(a == 0 || b == 0 || a == r-1 || b == c-1)
return true;
return false;
}
void bfs_fire()
{
int nx, ny;
fire now, next;
while(q.size()) {
now = q.front(); q.pop();
for(int i = 0; i < 4; ++i) {
nx = now.x+dx[i]; ny = now.y+dy[i];
next.x = nx; next.y = ny;
if(yes(nx, ny) && !vis[nx][ny]) {
vis[nx][ny] = vis[now.x][now.y] + 1;
q.push(next);
}
}
}
return;
}
void bfs(int px, int py)
{
int nx, ny;
while(q.size()) q.pop();
fire now, next;
now.x = px; now.y = py;
v[px][py] = 1;
q.push(now);
while(q.size()) {
now = q.front(); q.pop();
if(ended(now.x, now.y)) {
printf("%d\n", v[now.x][now.y]);
//printf("%d\n", now.t);
return;
}
for(int i = 0; i < 4; ++i) {
nx = now.x+dx[i]; ny = now.y+dy[i];
next.x = nx; next.y = ny; //next.t = now.t+1;
if(!v[nx][ny] && yes(nx, ny) &&
(v[now.x][now.y]+1 < vis[nx][ny] || vis[nx][ny] == 0) ) {
v[nx][ny] = v[now.x][now.y]+1;
q.push(next);
}
}
}
printf("IMPOSSIBLE\n");
return;
}
int main()
{
//freopen("in", "r", stdin);
scanf("%d", &T); //x是行,y是列
while(T--) {
int px, py;
fire f;
memset(vis, 0, sizeof(vis));
memset(v, 0, sizeof(v));
while(q.size()) q.pop();
scanf("%d %d", &r, &c);
for(int i = 0; i < r; ++i) {
scanf("%s", maze[i]);
for(int j = 0; j < c; ++j) {
if(maze[i][j] == 'F') {
f.x = i; f.y = j;
vis[f.x][f.y] = 1;
q.push(f);
}
if(maze[i][j] == 'J') {
px = i; py = j;
}
}
}
bfs_fire();
bfs(px, py);
}
return 0;
}