UVA11624 Fire!

本文介绍了一个使用C++实现的迷宫逃生模拟程序。通过两步广度优先搜索算法(BFS),分别模拟火灾蔓延和人物逃生过程,最终计算出人物逃离迷宫所需的最短时间。若无法逃脱,则输出“IMPOSSIBLE”。该程序适用于解决类似迷宫逃生的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

AC代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <queue>
using namespace std;

struct node{
    int x,y;
    int t;
    bool operator < (const node &a)const{
        return t > a.t;
    }
};
const int dx[] = {-1,0,1,0},dy[] = {0,-1,0,1};
int n,m;
char maze[1005][1005];
int visj[1005][1005],visf[1005][1005];

void bfs1(){
    memset(visf,-1,sizeof(visf));
    node cur;
    queue<node> q;
    for(int i = 0; i < n; i++){
        for(int j = 0; j < m; j++){
            if(maze[i][j] == 'F'){
                visf[i][j] = 0;
                q.push(node{i,j,0});
            }
        }
    }
    while(!q.empty()){
        cur = q.front();
        q.pop();
        for(int i = 0; i < 4; i++){
            int xx = cur.x+dx[i],yy = cur.y+dy[i];
            if(xx < 0 || xx >= n || yy < 0 || yy >= m || visf[xx][yy] != -1)
                continue;
            if(maze[xx][yy] != '#'){
                visf[xx][yy] = visf[cur.x][cur.y]+1;
                q.push(node{xx,yy,visf[xx][yy]});
            }
        }
    }
}

int bfs2(int x,int y){
    memset(visj,-1,sizeof(visj));
    node cur;
    visj[x][y] = 0;
    priority_queue<node> q;
    q.push(node{x,y,0});
    while(!q.empty()){
        cur = q.top();
        q.pop();
        if(cur.x == 0 || cur.x == n-1 || cur.y == 0 || cur.y == m-1){
            return cur.t+1;
        }
        for(int i = 0; i < 4; i++){
            int xx = cur.x+dx[i],yy = cur.y+dy[i];
            if(xx < 0 || xx >= n || yy < 0 || yy >= m || visj[xx][yy] != -1)
                continue;
            if(visf[xx][yy] != -1 && visj[cur.x][cur.y]+1 >= visf[xx][yy])
                continue;
            if(maze[xx][yy] != '#'){
                visj[xx][yy] = visj[cur.x][cur.y]+1;
                q.push(node{xx,yy,visj[xx][yy]});
            }
        }
    }
    return -1;
}
int main(){
    int T;
    scanf("%d",&T);
    while(T--){
        int jx,jy,fx,fy;
        scanf("%d%d",&n,&m);
        for(int i = 0; i < n; i++){
            scanf("%s",maze[i]);
            for(int j = 0; j < m; j++){
                if(maze[i][j] == 'J'){
                    jx = i;jy = j;
                }
            }
        }
        bfs1();//模拟火蔓延,尼玛这题有毒呀,火的位置不止一个
        int ans = bfs2(jx,jy);//模拟人
        if(ans < 0)
            printf("IMPOSSIBLE\n");
        else
            printf("%d\n",ans);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值