LQB2019A 4 迷宫

//
// Created by snnnom on 2020/9/5.
//

#include <iostream>
#include <stack>
#include <vector>
#include <math.h>
#include <string>
#include <stack>
#include <algorithm>
#include <climits>
#include <queue>
#define N 4
#define M 6
using namespace std;
struct point{
    int x;
    int y;
    string road="";
    point(int a,int b){
        x=a;
        y=b;
    }
};
char org[N][M];
bool vis[N][M];
int dx[4]={1,0,0,-1};
int dy[4]={0,-1,1,0};
char r[4]={'D','L','R','U'};
void bfs(){
    queue<point> p;
    point nowp(0,0);
    nowp.road="";//直接用road 记录所有的步数,这样就不用遍历了
    vis[0][0]=true;
    p.push(nowp);
    while(!p.empty()){
        point now=p.front();
        p.pop();
        //cout<<now.road<<endl;
        if(now.x==N-1 && now.y==M-1){
            cout<<now.road;
            break;
        }
        for (int i = 0; i < 4; ++i) {
            int nowx=now.x+dx[i];
            int nowy=now.y+dy[i];

            if(nowx>=0&&nowy>=0&&nowx<N&&nowy<M){

                if(org[nowx][nowy]=='0' && !vis[nowx][nowy]){
                    point pp(nowx,nowy);

                    vis[nowx][nowy]=true;
                    pp.road=now.road+r[i];
                    p.push(pp);//必须先改变road再push

                }
            }

        }
    }

}

int main(){
    for(int i=0;i<N;i++)
    {
        for(int j=0;j<M;j++)
            scanf("%c",&org[i][j]);
        getchar();//读掉回车
    }
    bfs();
    return 0;



}
为了自己,和那些爱你的人
原文地址:https://www.cnblogs.com/zhmlzhml/p/13716155.html