CSES - Shared codeLink to this code: https://cses.fi/paste/d297ff8fa88e0fd666dcf9/
#include<bits/stdc++.h>
using namespace std;
class Monsters{
int n,m,Ai,Aj;
vector<vector<char>>labyrinth;
vector<vector<int>>prev;
vector<vector<bool>>vis;
vector<int>X,Y;
queue<array<int,3>>que;
bool isValid(int x,int y){
return x>=0 and x<n and y>=0 and y<m and labyrinth[x][y]!='#' and !vis[x][y];
}
public:
Monsters(int n,int m,vector<vector<char>>&labyrinth){
this->n=n;
this->m=m;
this->labyrinth=labyrinth;
vis.resize(n,vector<bool>(m,0));
prev.resize(n,vector<int>(m,-1));
X={1,0,-1,0};
Y={0,1,0,-1};
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(labyrinth[i][j]=='M'){
que.push({i,j,0});
vis[i][j]=true;
}else if(labyrinth[i][j]=='A'){
Ai=i;
Aj=j;
vis[i][j]=true;
}
}
}
}
bool isGoal(int i,int j){
return (i==0 or i==n-1 or j==0 or j==m-1) and (labyrinth[i][j]=='.' or labyrinth[i][j]=='A');
}
string canReach(){
int x,y;
int goalX=-1,goalY=-1,len;
que.push({Ai,Aj,1});
while(!que.empty()){
len=que.size();
while(len--){
auto pos=que.front();
que.pop();
if(pos[2]==1 and isGoal(pos[0],pos[1])){
goalY=pos[1];
goalX=pos[0];
break;
}
for(int dir=0;dir<4;dir++){
x=pos[0]+X[dir];
y=pos[1]+Y[dir];
if(isValid(x,y)){
vis[x][y]=true;
que.push({x,y,pos[2]});
if(pos[2]==1)prev[x][y]=dir;
}
}
}
}
if(goalY==-1){
return "NO";
}
string direction;
while(goalX!=Ai or goalY!=Aj){
if(prev[goalX][goalY]==0)direction+="D";
else if(prev[goalX][goalY]==1)direction+="R";
else if(prev[goalX][goalY]==2)direction+="U";
else direction+="L";
x=goalX;
y=goalY;
goalX-=X[prev[x][y]];
goalY-=Y[prev[x][y]];
}
reverse(direction.begin(),direction.end());
return direction;
}
};
int main(){
int n,m;
cin>>n>>m;
vector<vector<char>>labyrinth(n,vector<char>(m));
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
cin>>labyrinth[i][j];
}
}
Monsters sol(n,m,labyrinth);
string ans=sol.canReach();
if(ans=="NO"){
cout<<ans<<endl;
}
else{
cout<<"YES\n"<<ans.size()<<endl<<ans<<endl;
}
return 0;
}