返回题解分享
讨论 / 题解分享/ 帖子详情

迷宫(结果填空) - 题解

#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
typedef pair<int,int> pii;
int n,m;
struct p{
    pii pre_point;
    char predir;
}pre[35][55];
string path="";
int dx[]={1,0,0,-1};
int dy[]={0,-1,1,0};
char map[]={'D','L','R','U'};
char g[35][55];
void bfs(){
    queue<pii> q;
    q.push({1,1});
    g[1][1]='1';
    while(q.size()){
        auto t=q.front();
        q.pop();
        for(int i=0;i<4;i++){
            int a=t.first+dx[i],b=t.second+dy[i];
            if(g[a][b]=='0'){
                q.push({a,b});
                g[a][b]='1';
                pre[a][b].predir=map[i];
                pre[a][b].pre_point=t;
            }
        }
    }
}
int main(){
    cin>>n>>m;
    for(int i=0;i<=n+1;i++){
        for(int j=0;j<=m+1;j++){
            g[i][j]='1';
        }
    }
    for(int i=1;i<=n;i++){
        for(int j=1;j<=m;j++){
            cin>>g[i][j];
        }
    }
    bfs();
    int a=n,b=m;
    while(pre[a][b].pre_point!=make_pair(1,1)){
        path+=pre[a][b].predir;
        int tempa=pre[a][b].pre_point.first,tempb=pre[a][b].pre_point.second;
        a=tempa,b=tempb;
        //cout<<a<<" "<<b<<endl;
        
    }
    path+=pre[a][b].predir;
    reverse(path.begin(),path.end());
    cout<<path<<endl;
    return 0;
}

//D<L<R<U 下左右上
//DRRURRDDDR 
//0223220002
0 回复 0 转发 0 喜欢 9 阅读
回复 (0)
默认 最新
暂无回复,快来抢沙发!