CSES - Shared codeLink to this code:
https://cses.fi/paste/dfd9fc301c9be88b1f65d5/
//REMEMBERING THE PAST , CAN AVOID REPEAT THE SAME
#include<bits/stdc++.h>
using namespace std;
#define mod 1000000007
#define inf 10000000000000000
typedef long long ll;
#define mp make_pair
#define f first
#define s second
// DP o Trees::http://cfrp.azurewebsites.net/blog/entry/20935
ll GCD(ll a,ll b){
ll maxi=max(a,b);
ll mini=min(a,b);
while(maxi && mini){
ll t=mini;
mini=maxi%mini;
maxi=t;
}
return max(maxi,mini);
}
ll power(ll x,ll y){
ll res=1;
while (y){
if (y & 1){
res=(res*x);
}
x=(x*x);
y=y>>1;
}
return res;
}
ll ncr(ll x, ll y){
ll ans=1;
y=(y > x-y? x-y: y);
for(ll i=0; i<y; i++){
ans=(ans*(x-i))%mod;
ans=(ans*power(i+1,mod-2))%mod;
ans=ans%mod;
}
return ans;
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n,m;
cin>>n>>m;
char mat[n][m];
bool visited[n][m];
memset(visited,false,sizeof(visited));
char direction[n][m];
pair<int,int> start,end;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
cin>>mat[i][j];
if(mat[i][j]=='A'){
start={i,j};
}
else if(mat[i][j]=='B'){
end={i,j};
}
}
}
queue<pair<int,int>> q;
q.push(start);
visited[start.f][start.s]=true;
int dx[]={1,-1,0,0};
int dy[]={0,0,1,-1};
pair<int,int> parent[n][m];
map<int,char> dir;
dir[0]='D';
dir[1]='U';
dir[2]='R';
dir[3]='L';
bool flag=false;
while(!q.empty()){
int x=q.front().f;
int y=q.front().s;
q.pop();
for(int i=0;i<4;i++){
int tx=x+dx[i],ty=y+dy[i];
if(tx>=0 && tx<n && ty>=0 && ty<m && !visited[tx][ty] && mat[tx][ty]!='#'){
visited[tx][ty]=true;
direction[tx][ty]=dir[i];
parent[tx][ty]={x,y};
if(mp(tx,ty)==end){
flag=true;
break;
}
q.push({tx,ty});
}
}
if(flag){
break;
}
}
if(flag){
cout<<"YES\n";
pair<int,int> son=end;
char prev;
string ans="";
while(son!=start){
prev=direction[son.f][son.s];
ans=prev+ans;
son=parent[son.f][son.s];
}
cout<<ans.size()<<"\n";
cout<<ans<<"\n";
}
else{
cout<<"NO\n";
}
return 0;
}