POJ 2312 Battle City (BFS状态搜索)

本文介绍了一种用于迷宫射击游戏中寻找从起点到终点最短路径的算法实现。该算法考虑到特殊地形的影响,并使用优先队列进行状态搜索,确保了效率。通过状态表示与剪枝策略的应用,有效地解决了复杂地图上的路径规划问题。

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

题意:

。。。

思路:

R和S是不能走的,遇到B时发射子弹和移动可以合并成一个代价为2的移动。

我们的状态是 [ 当前的位置, 已经消耗的时间 ]

状态用优先队列保存, 每次取出, 剪枝,  扩展

因为优先队列中取出的始终是 time 最小的状态,所以判断到达了终点就可以退出。

//#include<bits/stdc++.h>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <queue>
#include <stack>
#include <cassert>
#include <algorithm>
#include <cmath>
#include <climits>
#include <set>
#include <map>
using namespace std;

#define SPEED_UP iostream::sync_with_stdio(false);
#define FIXED_FLOAT cout.setf(ios::fixed, ios::floatfield);
#define rep(i, s, t) for(int (i)=(s);(i)<=(t);++(i))
#define urep(i, s, t) for(int (i)=(s);(i)>=(t);--(i))

typedef long long LL;

const int Maxn = 305;

char mm[Maxn][Maxn];
int n, m, t[Maxn][Maxn], sx, sy, ex, ey;

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

struct st{
    int x;
    int y;
    int t;
    st(int x, int y, int t):x(x), y(y), t(t){};
    inline bool operator < (const st& rhs) const {
        return t > rhs.t;
    }
};

inline int check(int x, int y) {
    return 0 <= x && x < n && 0 <= y && y < m;
}

void init() {
    rep(i, 0, n-1) {
        scanf("%s", mm[i]);
        rep(j, 0, m-1) {
            if (mm[i][j] == 'Y') sx = i, sy = j;
            else if (mm[i][j] == 'T') ex = i, ey = j;
        }
    }
}

void solve() {
    priority_queue<st> q;
    //queue<st> q;
    q.push( st(sx, sy, 0) );
    rep(i, 0, n-1)
        rep(j, 0, m-1) t[i][j] = INT_MAX;

    int x, y, old_t;
    t[sx][sy] = 0;
    while (!q.empty()) {
        st fr = q.top();q.pop();
        x = fr.x, y = fr.y, old_t = fr.t;

        if (x == ex && y == ey) {
            break;
            //continue;
        }
        int nx, ny, nt;
        rep(i, 0, 3) {
            nx = x + dx[i];
            ny = y + dy[i];
            nt = old_t + 1;
            // skip ?
            if (!check(nx, ny) || mm[nx][ny] == 'S' || mm[nx][ny] == 'R') continue;
            if (mm[nx][ny] == 'B') ++nt;
            if (nt >= t[ex][ey] || nt >= t[nx][ny]) continue;
            t[nx][ny] = nt;
            //cout << "going to " << nx << ", " << ny << endl;
            //cout << "time = " << nt << endl;
            q.push(st(nx, ny, nt));
        }
    }

    if (t[ex][ey] == INT_MAX) {
        printf("-1\n");
    }
    else {
        printf("%d\n", t[ex][ey]);
    }
}
int main() {
#ifndef ONLINE_JUDGE
    freopen("input.in", "r", stdin);
#endif
    //SPEED_UP
    while (scanf("%d%d",&n, &m) != EOF && (m && n)) {
        init();
        if (sx == ex && sy == ey) cout << '0' << endl;
        solve();
    }

    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值