学霸的迷宫

46 篇文章 0 订阅

思路:

广搜,记录路径,反向输出


#include <iostream>
#include <queue>
#include <stdio.h>
#include <algorithm>


using namespace std;
int mp[505][505];
char path[505][505];
int vis[505][505];
struct node
{
    int step,x,y;
};
 int n,m,ans;
queue <node>s;

int judge(int x,int y,int step)
{
    if(x>n||x<1||y>m||y<1||mp[x][y])
    {
        return 0;
    }
    if(vis[ x][ y]!=0&&vis[ x][ y]<= step)
        return 0;
    vis[x][y]=step;
    node t;
    t.x=x,t.y=y,t.step=step;
    s.push(t);
    return 1;
}
void bfs()
{
    while(!s.empty())
    {
        node t=s.front();
        s.pop();
        if(t.step>=ans)
        {
            break;
        }
        if(t.x==n&&t.y==m)
        {
            ans=t.step;
            continue;
        }
        vis[t.x][t.y]=t.step;
        if(judge(t.x+1,t.y,t.step+1))
        {
            path[t.x+1][t.y]='D';
        }
        if(judge(t.x,t.y-1,t.step+1))
        {
            path[t.x][t.y-1]='L';
        }
        if(judge(t.x,t.y+1,t.step+1))
        {
            path[t.x][t.y+1]='R';
        }
        if(judge(t.x-1,t.y,t.step+1))
        {
            path[t.x-1][t.y]='U';
        }
    }
}
char res[250005];
void printf_path()
{
    int stx,sty;
    stx=n,sty=m;
    while(stx!=1||sty!=1)
    {
        if(path[stx][sty]=='D')
            res[--ans]='D',stx--;
        else if(path[stx][sty]=='L')
            res[--ans]='L',sty++;
        else if(path[stx][sty]=='R')
            res[--ans]='R',sty--;
        else if(path[stx][sty]=='U')
            res[--ans]='U',stx++;
    }
    cout<<res<<endl;
}
int main()
{
    cin>>n>>m;
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=m;j++)
        {
            scanf("%1d",&mp[i][j]);

        }
    }

    node t;
    ans=0x3f3f3f3f;
    t.x=1,t.y=1,t.step=0;
    s.push(t);
    bfs();
    cout<<ans<<endl;
    printf_path();

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值