蓝桥杯迷宫c++

bfs问题

#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
#include <queue>
#include <cmath>
using namespace std;
const int N=30,M=50;
typedef long long ll;
typedef pair<int, int> PII;

char a[35][55];
queue<PII> q;
int st[35][55];
char s[35][55];

void print(int x,int y,char c){
    //cout << s[x][y] << endl;
    if(c!='D'&&c!='U'&&c!='L'&&c!='R')
        return;
    if(c=='D'){
        print(x - 1, y, s[x - 1][y]);
        printf("%c", s[x][y]);
    }
    else if(c=='L')
    {
         print(x, y + 1, s[x][y + 1]);
         printf("%c", s[x][y]);
    }  
    else if(c=='R'){
        print(x, y - 1, s[x][y - 1]);
        printf("%c", s[x][y]);
    }
    else if(c=='U'){
        print(x+1, y, s[x+1][y]);
         printf("%c", s[x][y]);
    }
    return;
    //cout << 2 << endl;
}

void bfs(){
    int dx[] = {1, 0, 0, -1}, dy[] = {0, -1, 1, 0};

    q.push({1, 1});
    st[1][1] = 1;
    while(q.size()){
        auto t = q.front();
        q.pop();
        //cout << q.size() << endl;
        //if(t.first==30&&t.second==50)

        for (int i = 0; i < 4;i++)
        {
            int x = t.first + dx[i], y = t.second + dy[i];
            if(a[x][y]=='0'&&x>0&&x<=N&&y>0&&y<=M&&st[x][y]==0)
            {
                q.push({x, y});
                if(i==0)
                    s[x][y] = 'D';
                else if(i==1)
                    s[x][y] = 'L';
                else if(i==2)
                    s[x][y] = 'R';
                else
                    s[x][y] = 'U';
                st[x][y] = 1;
            }
        }
    }

    //cout << 0 << endl;
}

int main()
{
    for (int i = 1; i <= N;i++)
    {
        for (int j = 1; j <= M;j++)
            scanf("%c", &a[i][j]);
        getchar();
    }
        
    //cout << 1 << endl;

    bfs();
    print(N,M, s[N][M]);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值