蓝桥杯(迷宫,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;
}
相关推荐
艾莉丝努力练剑2 小时前
【LeetCode&数据结构】单链表的应用——反转链表问题、链表的中间节点问题详解
c语言·开发语言·数据结构·学习·算法·leetcode·链表
_殊途4 小时前
《Java HashMap底层原理全解析(源码+性能+面试)》
java·数据结构·算法
还债大湿兄4 小时前
《C++内存泄漏8大战场:Qt/MFC实战详解 + 面试高频陷阱破解》
c++·qt·mfc
珊瑚里的鱼7 小时前
LeetCode 692题解 | 前K个高频单词
开发语言·c++·算法·leetcode·职场和发展·学习方法
AI+程序员在路上7 小时前
QTextCodec的功能及其在Qt5及Qt6中的演变
开发语言·c++·qt
Risehuxyc7 小时前
C++卸载了会影响电脑正常使用吗?解析C++运行库的作用与卸载后果
开发语言·c++
秋说8 小时前
【PTA数据结构 | C语言版】顺序队列的3个操作
c语言·数据结构·算法
lifallen9 小时前
Kafka 时间轮深度解析:如何O(1)处理定时任务
java·数据结构·分布式·后端·算法·kafka
liupenglove9 小时前
自动驾驶数据仓库:时间片合并算法。
大数据·数据仓库·算法·elasticsearch·自动驾驶
python_tty10 小时前
排序算法(二):插入排序
算法·排序算法