牛牛走迷宫(BFS)

牛牛走迷宫(BFS)

思路: B F S BFS 水题,按 L D R U LDRU 的顺序走就可以保证是最小字典序了。然后递归打印路径即可。

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=5e2+5,M=1e6+5,inf=0x3f3f3f3f,mod=1e9+7;
#define mst(a) memset(a,0,sizeof a)
#define lx x<<1
#define rx x<<1|1
#define reg register
#define PII pair<int,int>
#define fi first 
#define se second
int d[4][2]={1,0,0,-1,0,1,-1,0},n,m,vis[N][N];
char a[N][N];
struct node{
    int x,y,s;
}nw;
const string str=" DLRU";
void Print(int x,int  y){
	 if(x==1&&y==1) return;
	 if(vis[x][y]==1) Print(x-1,y);
	 else if(vis[x][y]==2) Print(x,y+1);
	 else if(vis[x][y]==3) Print(x,y-1);
	 else Print(x+1,y);
	 printf("%c",str[vis[x][y]]);
}
void bfs(){
    queue<node>q;
    nw={1,1,0};
    q.push(nw);
    vis[1][1]=1;
    while(q.size()){
         nw=q.front();q.pop();
         if(nw.x==n&&nw.y==m){
             printf("%d\n",nw.s);
             Print(n,m);
             return ;
         }
        for(int i=0;i<4;i++){
        	int nx=nw.x+d[i][0],ny=nw.y+d[i][1];
        	if(nx>=1&&nx<=n&&ny>=1&&ny<=m&&a[nx][ny]=='0'&&!vis[nx][ny])
        		 vis[nx][ny]=i+1,q.push({nx,ny,nw.s+1});
        }
    }
    puts("-1");
}
int main(){
	scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++)
    	for(int j=1;j<=m;j++)
    		scanf("\n%c",&a[i][j]);
    bfs();
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_45750972/article/details/106884451