蓝桥杯(迷宫,C++)

输入:

思路:

1、注意输入用字符串。

2、采用广度搜素的方法来求解。

3、因为最后要求字典序最小且D<L<R<U,所以在遍历四个方向的时候, 先向下,再向左、右,最后向上。

cpp 复制代码
#include<iostream>
#include<queue>
using namespace std;
int n, m;
string Map[500];
const int dire[4][2] = { {1,0},{0,-1},{0,1},{-1,0} };//下,左,右,上
const string d = "DLRU";
struct node
{
    int i, j;
    string ans;
};
queue<node> q;
void BFS()
{
    node s;
    s.i = 0, s.j = 0; s.ans = "";
    Map[0][0] = '1';
    q.push(s);
    while (!q.empty())
    {
        node a = q.front(), b;
        int x = a.i;//该点坐标
        int y = a.j;
        q.pop();
        if (x == n - 1 && y == m - 1)//走到终点
        {
            cout << a.ans.length() << endl;//步数
            cout << a.ans << endl;
            break;//最先达到的即为在步数最小的情况下,字典序最小
        }
        for (int i = 0; i < 4; i++)//遍历四个方向
        {
            int newx = x + dire[i][0];
            int newy = y + dire[i][1];
            if (newx < 0 || newy < 0 || newx >= n || newy >= m)//越界跳过
                continue;
            if (Map[newx][newy] == '0')//通路
            {
                b.ans = a.ans + d[i];//加上该次步骤
                b.i = newx, b.j = newy;
                Map[newx][newy] = '1';//标识已经走过
                q.push(b);//进入队列
            }
        }
    }
}
int main()
{
    cin >> n >> m;
    for (int i = 0; i < n; i++)
    {
        cin >> Map[i];
    }
    BFS();
   // cout << "DDDDRRURRRRRRDRRRRDDDLDDRDDDDDDDDDDDDRDDRRRURRUURRDDDDRDRRRRRRDRRURRDDDRRRRUURUUUUUUULULLUUUURRRRUULLLUUUULLUUULUURRURRURURRRDDRRRRRDDRRDDLLLDDRRDDRDDLDDDLLDDLLLDLDDDLDDRRRRRRRRRDDDDDDRR";
    return 0;
}
相关推荐
sycmancia几秒前
C++——C++异常处理
开发语言·c++
RuiBo_Qiu4 分钟前
【LLM进阶-后训练&部署】1. 大语言模型全参数微调:从前向推理到反向传播的底层原理解析
人工智能·算法·语言模型·自然语言处理·ai-native
HLC++4 分钟前
C++中的类和对象
开发语言·c++
橙子也要努力变强5 分钟前
Linux I/O 缓冲区、inode、软硬链接与磁盘结构全解析
linux·c++·操作系统
子有内涵5 分钟前
【Linux】程序地址空间(是什么?为什么?)
linux·运维·算法
setmoon2146 分钟前
C++与量子计算模拟
开发语言·c++·算法
实心儿儿11 分钟前
算法6:相交链表
数据结构·算法·链表
Amnesia0_013 分钟前
C++的异常
开发语言·c++·学习
nglff14 分钟前
蓝桥杯抱佛脚第二天|简单枚举,前缀和
算法·职场和发展·蓝桥杯
每天回答3个问题15 分钟前
LeetCodeHot100|链表总结
数据结构·c++·链表