Uva 11624 Fire!

分析

如果没有火,那么本题是一个标准的迷宫问题,可以用BFS解决。加上了火,难度增加没多少,由于起火便不会消失,我们可以预处理每个格子起火的时间,在BFS扩展结点时加一个判断,当到达的新结点没有着火时才加入队列。预处理实际上是一个最短路。

代码

#include <queue>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

const int N = 1111;
int n, m;
char Map[N][N];
bool vis[N][N];
int fire[N][N];
int X[] = {1,0,-1,0};
int Y[] = {0,1,0,-1};

struct Point{
    int x, y, t;
}s;
queue<Point>Q;

void init(){
    while(!Q.empty()) Q.pop();
    memset(vis, false, sizeof(vis));
    memset(fire, -1, sizeof(fire));
    for(int i = 0; i <= m+1; i++)
        Map[0][i] = '.';
    for(int i = 1; i <= n; i++){
        Map[i][0] = '.';
        scanf("%s", Map[i]+1);
        for(int j = 1; j <= m; j++){
            if(Map[i][j] == 'J'){
                s.x = i; s.y = j; s.t = 0;
            }
            else if(Map[i][j] == 'F'){
                Point tmp;
                tmp.x = i, tmp.y = j, tmp.t = 0;
                fire[tmp.x][tmp.y] = 0;
                Q.push(tmp);
            }
        }
        Map[i][m+1] = '.';
    }
    for(int i = 0; i <= m+1; i++)
        Map[n+1][i] = '.';
}

void BFS1(){
    while(!Q.empty()){
        Point st = Q.front();
        Q.pop();
        for(int i = 0; i < 4; i++){
            Point tmp = st;
            tmp.x += X[i]; tmp.y += Y[i]; tmp.t++;
            if(tmp.x <= 0 || tmp.x >= n+1 || tmp.y <= 0 || tmp.y >= m+1) continue;
            if(Map[tmp.x][tmp.y] == '#') continue;
            if(fire[tmp.x][tmp.y] >= 0) continue;

            fire[tmp.x][tmp.y] = tmp.t;
            Q.push(tmp);

        }
    }
}

void BFS2(int x, int y){
    Point st;
    st.x = x, st.y = y, st.t = 0;
    vis[x][y] = true;
    Q.push(st);
    int flag = 0;
    int ans = 0;
    while(!Q.empty()){
        st = Q.front();
        Q.pop();

        if(st.x == 0 || st.x == n+1 || st.y == 0 || st.y == m+1){
            flag = 1;
            ans = st.t;
            break;
        }

        for(int i = 0; i < 4; i++){
            Point tmp = st;
            tmp.x += X[i]; tmp.y += Y[i]; tmp.t++;
            if(tmp.x < 0 || tmp.x > n+1 || tmp.y < 0 || tmp.y > m+1) continue;
            if(Map[tmp.x][tmp.y] == '#') continue;
            if(vis[tmp.x][tmp.y]) continue;
            if(tmp.t >= fire[tmp.x][tmp.y] && fire[tmp.x][tmp.y] != -1) continue;

            vis[tmp.x][tmp.y] = true;
            Q.push(tmp);
        }
    }

    if(flag)  printf("%d\n", ans);
    else puts("IMPOSSIBLE");
}

int main (){
    int T;
    scanf("%d", &T);
    while(T--){
        scanf("%d %d", &n, &m);
        init();
        BFS1();
        BFS2(s.x, s.y);
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值