蓝桥杯(迷宫,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;
}
相关推荐
今天要早睡_1 分钟前
C++入门到精通:类和对象(下)全方位解析
android·c++
代码不停6 分钟前
BFS算法解决FloodFill问题
算法·bfs·宽度优先
艾莉丝努力练剑9 分钟前
【AI大模型接入SDK】ChatSDK架构设计与实现
网络·c++·人工智能·学习·语言模型
重生之小比特13 分钟前
【C++进阶】红黑树的实现
java·开发语言·c++
纪念 22914 分钟前
C++算法(一)
开发语言·c++·算法
All for pursuit.34 分钟前
【二叉树-10】114.二叉树展开为链表
数据结构·c++·算法·leetcode·链表
叠层归一研究院35 分钟前
区分预算与通道诱导:Ω–L叠层体系的观测赋值与定量验证
人工智能·算法
多弗朗皮卡丘38 分钟前
C++string类
c++
BYSJMG1 小时前
计算机毕业设计选题推荐:基于大数据的快递物流运营数据分析与可视化,Spark与K-Means
大数据·算法·数据分析·spark·课程设计
阳明山水2 小时前
因果一致性正则化实战解析
人工智能·深度学习·算法·机器学习·架构