蓝桥杯(迷宫,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;
}
相关推荐
~|Bernard|10 小时前
二.go语言中map的底层原理(2026-5-8)
算法·golang·哈希算法
AbandonForce10 小时前
哈希表(HashTable,散列表)个人理解
开发语言·数据结构·c++·散列表
mask哥10 小时前
力扣算法java实现汇总整理(下)
java·算法·leetcode
样例过了就是过了10 小时前
LeetCode热题100 编辑距离
数据结构·c++·算法·leetcode·动态规划
z2005093010 小时前
C++中位图和布隆过滤器的一些面试题
开发语言·c++
wearegogog12310 小时前
MATLAB椭圆参数检测算法实现
数据库·算法·matlab
secondyoung10 小时前
Markdown数学公式语法速查手册
算法·编辑器·markdown·latex
君义_noip11 小时前
CSP-S 2025 提高级 第一轮(初赛) 阅读程序(1)
算法·深度优先·信息学奥赛·初赛
小O的算法实验室11 小时前
2026年IEEE TEVC,知识引导的竞争进化算法用于多解传感器-武器-目标分配问题,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
khalil102011 小时前
代码随想录算法训练营Day-46 动态规划13 | 647. 回文子串、516.最长回文子序列、动态规划总结
数据结构·c++·算法·leetcode·动态规划·回文子串·回文子序列