bfs+状态记录(扩展标记实现)

本文介绍了一种使用广度优先搜索(BFS)解决迷宫问题的方法,并通过扩展标记来记录状态,确保算法能够有效地遍历迷宫地图,避开障碍物并利用钥匙打开门。该方法特别适用于需要寻找最短路径的问题。

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

广搜并记录状态,通过扩展标记实现

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

char map[22][22];
bool  vis[22][22][1024];
int n, m, t, sx, sy, sz;
int dirx[] = { 1,-1,0,0 };
int diry[] = { 0,0,1,-1 };

struct Node
{
    int x, y, cost, key;
};

int bfs()
{
    queue<Node>Q;
    Node a, e;
    memset(vis, false, sizeof(vis));
    a.x = sx;
    a.y = sy;
    a.cost = 0;
    a.key = 0;
    vis[a.x][a.y][a.key]=true;
    Q.push(a);
    while (!Q.empty())
    {
        a = Q.front();
        Q.pop();
        if (map[a.x][a.y] == '^'&&a.cost < t)
        {
            return a.cost;
        }
        if (a.cost >= t)
        {
            return -1;
        }
        for (int i = 0;i < 4;i++)
        {
            e.key = a.key;
            e.x = a.x + dirx[i];
            e.y = a.y + diry[i];
            e.cost = a.cost + 1;
            if (e.x >= 0 && e.x < n && e.y >= 0 && e.y < m && map[e.x][e.y] != '*')
            {
                if (map[e.x][e.y] >= 'A'&&map[e.x][e.y] <= 'J')
                {
                    int key = (map[e.x][e.y] - 'A');
                    if (((e.key >> key) & 1) && !vis[e.x][e.y][e.key])
                    {
                        vis[e.x][e.y][e.key]=true;
                        Q.push(e);
                    }
                }
                else if (map[e.x][e.y] >= 'a'&&map[e.x][e.y] <= 'j')
                {
                    int key = (1 << (map[e.x][e.y] - 'a'));
                    e.key = (e.key | key);
                    if (!vis[e.x][e.y][e.key])
                    {
                        vis[e.x][e.y][e.key]=true;
                        Q.push(e);
                    }
                }
                else
                {
                    if (!vis[e.x][e.y][e.key])
                    {
                        vis[e.x][e.y][e.key]=true;
                        Q.push(e);
                    }
                }
            }
        }
    }
    return -1;
}

int main()
{
    while (~scanf("%d %d %d", &n, &m, &t))
    {
        for (int i = 0;i < n;i++)
        {
            scanf("%s", map[i]);
            for (int j = 0;j < m;j++)
                if (map[i][j] == '@') sx = i, sy = j;
        }
        printf("%d\n", bfs());
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值