蓝桥杯(迷宫,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;
}
相关推荐
小白菜又菜36 分钟前
Leetcode 3432. Count Partitions with Even Sum Difference
算法·leetcode
wuhen_n2 小时前
LeetCode -- 15. 三数之和(中等)
前端·javascript·算法·leetcode
sin_hielo2 小时前
leetcode 2483
数据结构·算法·leetcode
Xの哲學3 小时前
Linux多级时间轮:高精度定时器的艺术与科学
linux·服务器·网络·算法·边缘计算
大头流矢3 小时前
归并排序与计数排序详解
数据结构·算法·排序算法
阿闽ooo3 小时前
外观模式:从家庭电源控制看“简化接口“的设计智慧
c++·设计模式·外观模式
油泼辣子多加3 小时前
【信创】算法开发适配
人工智能·深度学习·算法·机器学习
Aaron15884 小时前
AD9084和Versal RF系列具体应用案例对比分析
嵌入式硬件·算法·fpga开发·硬件架构·硬件工程·信号处理·基带工程
laocooon5238578864 小时前
插入法排序 python
开发语言·python·算法
你的冰西瓜4 小时前
C++中的list容器详解
开发语言·c++·stl·list