hdu1728 逃离迷宫 --bfs

题目链接:hdu1728

还是bfs走迷宫, 但不再是求最短路,而是问能不能在k次转向内从出发点走到目标点.

初始方向不计入次数,可以直接把四个方向全push
队列节点的次数都限制在k次以内,大于k就不用push了

#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;

const int MAXN = 110;

struct node {
    int turn, dir, x, y;
    node() {}
    node(int t, int d, int _x, int _y):turn(t), dir(d), x(_x), y(_y) {}
    friend bool operator<(const node &a, const node &b) {
        return a.turn < b.turn;
    }
};

char mp[MAXN][MAXN];
int book[4][MAXN][MAXN];
int nx[] = {-1, 0, 1, 0};
int ny[] = {0, 1, 0, -1};

bool bfs(int k, int sx, int sy, int ex, int ey, int m, int n) {
    priority_queue<node> q;
    memset(book, 0x3f, sizeof(book));
    q.push(node(0, 0, sx, sy)); 
    q.push(node(0, 1, sx, sy)); 
    q.push(node(0, 2, sx, sy)); 
    q.push(node(0, 3, sx, sy)); 

    while (!q.empty()) {
        node t = q.top();
        q.pop();
        if (t.x == ex && t.y == ey)
            return true;
        for (int i = 0; i < 4; i++) {
            int tx = t.x + nx[i];
            int ty = t.y + ny[i];
            if (tx < 1 || tx > m || ty < 1 || ty > n || mp[tx][ty] == '*')
                continue;
            int nturn = t.turn;
            if (i != t.dir)
                nturn++;
            if (nturn <= k && nturn < book[i][tx][ty]) {
                q.push(node(nturn, i, tx, ty));
                book[i][tx][ty] = nturn;
            }
        }
    }
    return false;
}

int main() {
    int T;
    scanf("%d", &T);
    while (T--) {
        int m, n;
        scanf("%d%d", &m, &n);
        getchar();
        for (int i = 1; i <= m; i++)
            fgets(mp[i]+1, MAXN, stdin);

        int k, sx, sy, ex, ey;
        scanf("%d%d%d%d%d", &k, &sx, &sy, &ex, &ey);
        puts(bfs(k, sy, sx, ey, ex, m, n)?"yes":"no");
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值