CSES – Monsters

BFS

#include<bits/stdc++.h>
#define int long long
#define f first
#define s second
#define fastio ios_base::sync_with_stdio(0);cin.tie(0)
using namespace std;
//declare
const int maxn = 1005;
int n,m,a,b,step[maxn][maxn],mstep[maxn][maxn];
char maze[maxn][maxn];
queue<pair<int,int>> q,mq;
int dir[4][2] = {{0,1},{0,-1},{-1,0},{1,0}};
pair<int,int> from[maxn][maxn], ans = {-1,-1};
//
void mbfs(){
    while(!mq.empty()){
        int x = mq.front().f, y = mq.front().s; mq.pop();
        for(int i=0;i<4;i++){
            int newx = x+dir[i][0], newy = y+dir[i][1];
            if(maze[newx][newy] == '#') continue;
            if(maze[newx][newy] == 'S') continue;
            if(mstep[newx][newy] != 1e18) continue;
            mstep[newx][newy] = mstep[x][y] + 1;
            from[newx][newy] = {x,y};
            mq.push({newx,newy});
        }
    }
}
void bfs(){
    while(!q.empty()){
        int x = q.front().f, y = q.front().s; q.pop();
        if(maze[x][y] == 'S'){
            ans = {x,y};
            return;
        }
        for(int i=0;i<4;i++){
            int newx = x+dir[i][0], newy = y+dir[i][1];
            if(maze[newx][newy] == '#') continue;
            if(step[newx][newy] != -1) continue;
            if(mstep[newx][newy] <= step[x][y] + 1) continue;
            step[newx][newy] = step[x][y] + 1;
            from[newx][newy] = {x,y};
            q.push({newx,newy});
        }
    }
}
void print(int x,int y){
    if(x == a && y == b){
        return;
    }
    print(from[x][y].f, from[x][y].s);
    if(from[x][y].f == x){
        if(from[x][y].s == y+1) cout<<'L';
        else cout<<'R';
    }
    else{
        if(from[x][y].f == x+1) cout<<'U';
        else cout<<'D';
    }
}
signed main(){
    fastio;
    cin>>n>>m;
    memset(step,-1,sizeof(step));
    memset(maze,'S',sizeof(maze));
    for(int i=0;i<=n+1;i++) for(int j=0;j<=m+1;j++) mstep[i][j] = 1e18;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=m;j++){
            cin>>maze[i][j];
            if(maze[i][j] == 'M'){
                mstep[i][j] = 0;
                mq.push({i,j});
            }
            if(maze[i][j] == 'A'){
                step[i][j] = 0;
                a = i, b = j;
                q.push({i,j});
            }
        }
    }
    mbfs();
    bfs();
    if(ans == make_pair(-1ll,-1ll)) cout<<"NO";
    else{
        cout<<"YES\n"<<step[ans.f][ans.s]-1<<"\n";
        print(from[ans.f][ans.s].f,from[ans.f][ans.s].s);
    }
    cout<<"\n";
    return 0;
}

相關文章

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *