蓝桥杯 省赛 填空题 迷宫 带路径的BFS 对结构体的妙用 路径存储

题目

题目地址

题解思路

首先按字典序最小无非就是按这种顺序走,DFS中也是一样的。BFS本来可以更快解决迷宫类最短路的问题,但路径怎么处理呢,我想出了一种比较憨的办法,多用一个string变量(还是不太会用string然后看了别人的代码发现果然有人和我想的一样)记录每次的路径。 这里对结构体内置函数的处理真的巧妙,原来是让数值更方便的存进去。比如这样

struct node
{
   int x,y,step;
   string s;
   	node(int xx,int yy,int sttep,string ss)
	{
		x = xx;y = yy;s = ss;step =sttep;
	}
};
    queue <node > lu;
    lu.push(node(0,0,0,"")); //像这样 真是巧妙 

其他操作就和BFS相同了每次再多一个变量加上路径即可

 if(mp[fx][fy] != '1'&&fx >= 0&&fx < 30&&fy >= 0&&fy < 50&&vis[fx][fy] == 0)
            {
                vis[fx][fy] = 1;
                lu.push(node(fx,fy,t.step+1,t.s+xu[i]));
            }

AC代码

#include <iostream>
#include <cstdio>
#include <queue>
#include <string>
using namespace std;
struct node
{
   int x,y,step;
   string s;
   	node(int xx,int yy,int sttep,string ss)
	{
		x = xx;y = yy;s = ss;step =sttep;
	}
};
char mp[33][55];
bool vis[33][55];
int dx[4] = {1,0,0,-1};
int dy[4] = {0,-1,1,0};
char xu[4] = {'D','L','R','U'};
int main()
{
    queue <node > lu;
    for(int i=0;i<30;i++)
            cin>>mp[i];
    vis[0][0] = 1;
    lu.push(node(0,0,0,""));
    while(!lu.empty())
    {
        node t=lu.front();
        if( t.x == 29 && t.y == 49)
        {
            cout<<t.s<<"\n";
            return 0;
        }
        for(int i = 0;i < 4; i++)
        {
            int fx = t.x + dx[i];
            int fy = t.y + dy[i];
            if(mp[fx][fy] != '1'&&fx >= 0&&fx < 30&&fy >= 0&&fy < 50&&vis[fx][fy] == 0)
            {
                vis[fx][fy] = 1;
                lu.push(node(fx,fy,t.step+1,t.s+xu[i]));
            }
        }
        lu.pop();
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值