bfs记录路径,蓝桥杯真题

题意:在01矩阵中,找到一条从入口到终点的最短路径,并且打印这条路径。

题目链接:http://lx.lanqiao.cn/problem.page?gpid=T291

#include<iostream>
#include<queue>
#include<cstring>
using namespace std;

int vis[505][505];
int map[505][505];
int n,m;


struct node{
    int x;
    int y;
    int dis;   //到达这个点的距离 
};
queue<node>q;

struct father{
    int x;
    int y;
    char dir;    //到达这个点的方式 
}path[505][505];

bool judge(node nn)
{
    if(nn.x<1||nn.x>n||nn.y<1||nn.y>m||map[nn.x][nn.y]==1||vis[nn.x][nn.y]==1)
    {
        return false;
    }
    return true;
}

char judge_dir(int k)
{
    if(k==0)
    {
        return 'D';
    }
    if(k==1)
    {
        return 'L';
    }
    if(k==2)
    {
        return 'R';
    }
    if(k==3)
    {
        return 'U';
    }
}

int dx[4]={1,0,0,-1};//下(D),左(L),右(R),上(U) 
int dy[4]={0,-1,1,0};

int bfs()
{
    memset(vis,0,sizeof(vis));
    while(!q.empty())
    {
        q.pop();
    }
     node nn;
     nn.x=1;
     nn.y=1;
     nn.dis=0;
     vis[1][1]=1;
     q.push(nn);
     while(!q.empty())
     {
         node t=q.front();
         q.pop();
         for(int k=0;k<4;k++)
         {
             node next;
             next.x=t.x+dx[k];
             next.y=t.y+dy[k];
             next.dis=t.dis+1;
             if(judge(next))
             {
                 //cout<<"next "<<next.x<<' '<<next.y<<endl;
                 q.push(next);
                 vis[next.x][next.y]=1;
                 path[next.x][next.y].x=t.x;
                 path[next.x][next.y].y=t.y;
                 path[next.x][next.y].dir=judge_dir(k);
                 if(next.x==n&&next.y==m)
                 {
                     return next.dis; 
                }
            }
        }
     }
     return -1;
}

void print_path(int xx,int yy)
{
    if(xx==1&&yy==1)
    {
        return;
    }
    print_path(path[xx][yy].x,path[xx][yy].y);
    //cout<<"xx"<<xx<<endl;
    //cout<<"yy"<<yy<<endl; 
    cout<<path[xx][yy].dir;
    
}

int main()
{
    cin>>n>>m;
    getchar();
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=m;j++)
        {
            char ch=getchar();
            map[i][j]=ch-'0';
        }
        getchar();
    }    
    int ans=bfs();
    cout<<ans<<endl;
    print_path(n,m);
    return 0;
} 

 

转载于:https://www.cnblogs.com/hang-shao/p/10519824.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值