CSES - Shared codeLink to this code:
https://cses.fi/paste/66006de0f5ef7d3efadee/
#include <bits/stdc++.h>
using namespace std;
#define endl ("\n")
#define pi (3.141592653589)
#define mod 1000000007
#define int long long
#define pb push_back
#define mp make_pair
#define ff first
#define ss second
#define rep(i,n) for(int i=0;i<n;i++)
#define fast ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
bool valid(int row, int cols, int n, int m){
return (row >= 0 && row < n && cols >= 0 && cols < m);
}
int32_t main(){
fast
// freopen("input.txt","r",stdin);
// freopen("output.txt","w",stdout);
int t=1;
// cin>>t;
while(t--){
int n, m;cin>>n>>m;
int row[4] = {1, -1, 0, 0};
int col[4] = {0, 0, 1, -1};
vector<vector<char>>v(n, vector<char>(m));
int vis[n][m];rep(i, n)rep(j, m)vis[i][j]=0;
pair<int, int>start;
rep(i, n){
rep(j, m){
cin>>v[i][j];
if(v[i][j]=='A')start=mp(i, j);
}
}
list<pair<int, int>> q;
vis[start.ff][start.ss]=1;
q.pb(start);
map<pair<int, int>, pair<pair<int, int>,char>>parent;
while (!q.empty())
{
auto s=q.front();
int a=s.ff, b=s.ss;
q.pop_front();
for(auto i :row){
for(auto j :col){
if(valid(a+i, b+j, n, m) and (abs(i) != abs(j)) and !vis[a+i][b+j] and (v[a+i][b+j] == '.' or v[a+i][b+j] == 'B') ){
char c;
if(i==1 and j==0)
c= 'D';
if(i==-1 and j==0)
c='U';
if(j==1 and i==0)
c='R';
if(j==-1 and i==0)
c='L';
parent[mp(a+i, b+j)]=mp(mp(a, b),c);
if(v[a+i][b+j] == 'B'){
auto end = make_pair(a+i, b+j);
string res = "";
while(true){
res += parent[end].ss;
end = parent[end].ff;
if(end.ff == start.ff and end.ss == start.ss){
break;
}
}
reverse(res.begin(), res.end());
cout<<"YES"<<endl;
cout<<res.length()<<endl;
cout<<res;
return 0;
}
vis[a+i][b+j]=1;
q.pb(mp(a+i, b+j));
}
}
}
}
cout<<"NO";
}
return 0;
}