UVA 11624 - Fire!(BFS)

题目:

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值