hdu1728

本文深入探讨了一种基于优先队列的迷宫寻路算法,通过定义节点结构和距离矩阵,利用广度优先搜索(BFS)策略,实现从起点到终点的路径寻找。特别关注了行和列的坐标转换问题,避免常见的编程陷阱。

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

/**/
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cctype>
#include <iostream>
#include <algorithm>
#include <map>
#include <set>
#include <vector>
#include <string>
#include <stack>
#include <queue>

typedef long long LL;
using namespace std;

int n, m, flag;
int k, x1, x2, y1, y2;
char s[105][105];
int dist[4][2] = {1, 0, -1, 0, 0, -1, 0, 1};

struct node{
    int x, y, w;
    bool operator <(const node &a) const {
        return w > a.w;
    }
};

void bfs(){
    int vis[105][105];
    memset(vis, 0, sizeof(vis));
    priority_queue<node> q;
    q.push(node{x1, y1, -1});
    while(q.size()){
        node t = q.top();
        q.pop();
        //if(t.x == x2 && t.y == y2){
        //    if(t.w <= k){
        //        printf("yes\n");
            //    flag = 1;
            //}
        //    return ;
        //}
        for (int i = 0; i < 4; i++){
            int x = t.x + dist[i][0], y = t.y + dist[i][1];
            while(!(x < 1 || x > n || y < 1 || y > m || s[x][y] == '*')){
                if(!vis[x][y] || vis[x][y] > t.w + 1){
                    vis[x][y] = t.w + 1;
                    q.push(node{x, y, t.w + 1});
                    if(x == x2 && y == y2 && t.w + 1 <= k){
                        printf("yes\n");
                        flag = 1;
                        return ;
                    }
                }
                x += dist[i][0], y += dist[i][1];
            }
            
        }
    }
}

int main(){
    int t;
    scanf("%d", &t);
    while(t--){
        scanf("%d %d", &n, &m);
        for (int i = 1; i <= n; i++){
            scanf("%s", s[i] + 1);
        }
        scanf("%d %d %d %d %d",&k, &y1, &x1, &y2, &x2);
        if(s[x2][y2] == '*'){
            printf("no\n");
            continue;
        }
        flag = 0;
        bfs();
        if(!flag){
            printf("no\n");
        }
    }
    return 0;
}
/**/

注意行和列反过来!!多坑啊

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值