蓝桥杯(迷宫,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;
}
相关推荐
Zachery Pole8 小时前
CCF-CSP备战NO.7【队列】
算法
闪电悠米9 小时前
力扣hot100-48.旋转图像-转置翻转详解
算法·leetcode·职场和发展
满天星83035779 小时前
【算法】最长递增子序列(三种解法)
算法
hold?fish:palm9 小时前
kv存储主从复制的设计与实现
c++·redis·后端
啦啦啦啦啦zzzz9 小时前
算法:贪心算法
c++·算法·leetcode·贪心算法
charlie11451419110 小时前
现代C++工程实践 WeakPtr 实战(三):WeakPtrFactory 与「最后成员」惯用法
开发语言·c++·开源项目·现代c++
清泓y11 小时前
RAG 技术
算法·ai
阿慧今天瘦了嘛11 小时前
计算机组成原理概述:从硬件到软件的桥梁
计算机网络·算法
JetComXCpp11 小时前
给 Win32 窗口加上毛玻璃效果——纯 D3D11 实现,零依赖
c++
网站优化(SEO)专家12 小时前
SEO核心算法拆解:网站排名快速提升的武林秘籍!
算法·搜索引擎·网站排名·核心算法