大火蔓延的迷宫(Fire!, UVa 11624)

该博客介绍了如何解决UVa 11624编程挑战,即大火在迷宫中蔓延的问题。通过搜索算法探讨如何避免火势扩散并寻找解决方案。

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

大火蔓延的迷宫(Fire!, UVa 11624)

白书5.1 例题1

FireUVA11624
Code:

#include <cstdio>
#include <cstring>
#include <string>
#include <queue>

using namespace std;
const int N = 1000 + 5;
char mp[N][N];
bool vis[N][N];
int T, R, C;

struct node {
    int x, y, step, state;  //state  0是火 1是人

    node(int x, int y, int step, int state) : x(x), y(y), step(step), state(state) {}
};

int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0, -1};

int bfs() {
    queue<node> Q;
    for (int i = 1; i <= R; i++)
        for (int j = 1; j <= C; j++)
            if (mp[i][j] == 'F') {
                Q.push(node(i, j, 0, 0));
                vis[i][j] = true;
            }
    for (int i = 1; i <= R; i++)
        for (int j = 1; j <= C; j++)
            if (mp[i][j] == 'J') {
                Q.push(node(i, j, 0, 1));
                vis[i][j] = true;
            }

    while (!Q.empty()) {
        node now = Q.front();
        Q.pop();
        if (now.state == 1 && (now.x == 1 || now.x == R || now.y == 1 || now.y == C)) return now.step + 1;
        for (int i = 0; i < 4; i++) {
            int x = now.x + dx[i], y = now.y + dy[i];
            if (x < 1 || x > R || y < 1 || y > C || vis[x][y] || mp[x][y] == '#') continue;
            Q.push(node(x, y, now.step + 1, now.state));
            vis[x][y] = true;
        }
    }
    return 0;
}

int main() {
#ifdef ONLINE_JUDGE
#else
    freopen("in.txt", "r", stdin);
#endif

    scanf("%d", &T);
    while (T--) {
        scanf("%d%d", &R, &C);
        memset(mp, '\0', sizeof(mp));
        memset(vis, 0, sizeof(vis));
        for (int i = 1; i <= R; i++)
            scanf("%s", mp[i] + 1);
        int ans = bfs();
        if (ans) printf("%d\n", ans);
        else printf("IMPOSSIBLE\n");
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值