蓝桥杯 学霸的迷宫

问题描述
  学霸抢走了大家的作业,班长为了帮同学们找回作业,决定去找学霸决斗。但学霸为了不要别人打扰,住在一个城堡里,城堡外面是一个二维的格子迷宫,要进城堡必须得先通过迷宫。因为班长还有妹子要陪,磨刀不误砍柴功,他为了节约时间,从线人那里搞到了迷宫的地图,准备提前计算最短的路线。可是他现在正向妹子解释这件事情,于是就委托你帮他找一条最短的路线。
输入格式
  第一行两个整数n, m,为迷宫的长宽。
  接下来n行,每行m个数,数之间没有间隔,为0或1中的一个。0表示这个格子可以通过,1表示不可以。假设你现在已经在迷宫坐标(1,1)的地方,即左上角,迷宫的出口在(n,m)。每次移动时只能向上下左右4个方向移动到另外一个可以通过的格子里,每次移动算一步。数据保证(1,1),(n,m)可以通过。
输出格式
  第一行一个数为需要的最少步数K。
  第二行K个字符,每个字符∈{U,D,L,R},分别表示上下左右。如果有多条长度相同的最短路径,选择在此表示方法下字典序最小的一个。
样例输入
Input Sample 1:
3 3
001
100
110

Input Sample 2:
3 3
000
000
000
样例输出
Output Sample 1:
4
RDRD

Output Sample 2:
4
DDRR
数据规模和约定
  有20%的数据满足:1<=n,m<=10
  有50%的数据满足:1<=n,m<=50
  有100%的数据满足:1<=n,m<=500。
 
 
分析:基本的BFS   另外,要记录一下路径,所以采用了string 方便每次路径的添加。
 
代码如下
#include <bits/stdc++.h>
using namespace std;
int  move1[4][2]={-1,0,1,0,0,1,0,-1};
char map1[600][600];
int vis[600][600];
 int n,m;
struct node
{
    int x;
    int y;
    int step;
    string c;
};
int check(int x,int y)
{
    if(x>=0&&y>=0&&x<n&&y<m&&map1[x][y]=='0'&&!vis[x][y])
    return 1;
    return 0;
}
void bfs()
{
  queue<node>Q;
      node a,next;
      a.x=0;
      a.y=0;
    a.step=0;
    Q.push(a);
    while(!Q.empty())
    {
     //puts("1");
       a=Q.front();
       if(a.x==n-1&&a.y==m-1)
       {
           cout<<a.step<<endl;
           cout<<a.c<<endl;
       } 
       Q.pop();
       
        next.x=a.x+1;
       next.y=a.y;
       if(check(next.x,next.y))
       {
                vis[next.x][next.y]=1;
             next.step=a.step+1;
             next.c=a.c+'D';
              Q.push(next);
       }
       
          next.x=a.x;
       next.y=a.y-1;
       
       if(check(next.x,next.y))
       {
                vis[next.x][next.y]=1;
             next.step=a.step+1;
             next.c=a.c+'L';
             Q.push(next);
       }
    
    
    // puts("3");
        next.x=a.x;
       next.y=a.y+1;
     //  cout<<" "<<vis[0][1]<<endl;
     //  cout<<" "<<map1[0][1]<<endl;
     //  cout<<next.x<<" "<<next.y<<endl;
       if(check(next.x,next.y))
       {
       //    puts("2");
           vis[next.x][next.y]=1;
             next.step=a.step+1;
             next.c=a.c+'R';
              Q.push(next);
    
      } 
    
    
     next.x=a.x-1;
       next.y=a.y;
       if(check(next.x,next.y))
       {
                vis[next.x][next.y]=1;
             next.step=a.step+1;
             next.c=a.c+'U';
              Q.push(next);
       }
       
      
       
       
      
       }
   
}
int main()
{
    cin>>n>>m;
    
        memset(vis,0,sizeof(vis));
        for(int i=0;i<n;i++)
          cin>>map1[i];
          vis[0][0]=1;
        bfs();
     
   
}
原文地址:https://www.cnblogs.com/a249189046/p/6639389.html