NYOJ483噩梦(优先队列 + 无标记)

本文详细解析了一个ACM竞赛题目,介绍了如何通过广度优先搜索(BFS)算法解决迷宫问题,特别注意了在访问特定节点时的状态重置条件,以避免重复访问。

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


本题重点是访问完一次4之后要置成1或者0,防止多次重置。

因为这个我错了好多次。



代码:

#include <cstdio>
#include <queue>
#include <cstring>
#include <vector>
#include <algorithm>

using namespace std;

typedef struct {
    int x,y;
    int time;
    int step;
}node;
node st;
int n,m;
int a[10][10];

int enx,eny;

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

struct cmp{
    bool operator()(node i,node j)
    {
        return i.step > j.step;
    }
};
int bfs()

{
    priority_queue<node,vector<node>,cmp> q;
    node t,head;
    st.time = 6;
    st.step = 0;
    q.push(st);
    while(!q.empty())
    {
        head = q.top();
        q.pop();
       // printf("%d %d %d %d\n",head.x,head.y,head.time,head.step);
        if(head.time == 1)
            continue;
        if(head.x == enx && head.y == eny && head.time > 0)
        {
            return head.step;
        }
        for(int i = 0;i < 4;++i)
        {
            t.x = head.x + dx[i];
            t.y = head.y + dy[i];
            t.step = head.step + 1;
            t.time = head.time - 1;
            if(t.x >= 1 && t.x <= n && t.y >= 1 && t.y <= m && a[t.x][t.y])
            {
                if(a[t.x][t.y] == 4 && t.time > 0)
                {
                     a[t.x][t.y] = 1;
                     t.time = 6;
                }

                else if(a[t.x][t.y] == 3 && t.time > 0)
                {
                    return t.step;
                }
                q.push(t);
            }
        }
    }
    return -1;
}
int main()

{
    int t;
    scanf("%d",&t);
    while(t--)
    {
       // memset(v,0,sizeof(v));
        scanf("%d%d",&n,&m);
        for(int i = 1;i <= n;++i)
        {
            for(int j = 1;j <= m;++j)
            {
                scanf("%d",&a[i][j]);
                if(a[i][j] == 2)
                {
                    st.x = i;
                    st.y = j;
                }
                else if(a[i][j] == 3)
                {
                    enx = i;
                    eny = j;
                }
            }
        }
        printf("%d\n",bfs());
       // printf("%d %d %d %d\n",stx,sty,enx,eny);

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值