CSES - Shared codeLink to this code:
https://cses.fi/paste/0c68129b81b0a8252c88f4/
#include <bits/stdc++.h>
using namespace std;
struct obj{
int i;
int j;
string s;
obj* o;
obj(int,int,string,obj*);
};
obj::obj(int _i,int _j, string _s, obj* _o){
this->i = _i;
this->j = _j;
this->s = _s;
this->o = _o;
}
bool check(int x, int y, int n, int m, vector<vector<int>> const &lab, vector<vector<int>> &seen){
if(x >= 0 && y >= 0 && x < n && y < m && lab[x][y] && !seen[x][y]){
seen[x][y] = 1;
return true;
}
return false;
}
int main(){
int n,m; cin >> n >> m;
pair<int,int> A,B;
vector<vector<int>> lab(n,vector<int>(m,0));
for(int i=0;i<n;i++){
string s; cin >> s;
for(int j=0;j<s.size();j++){
if(s[j] == 'A'){
A.first = i; A.second = j;
}
else if(s[j] == 'B'){
B.first = i; B.second = j;
lab[i][j] = 2;
}
else if(s[j] == '.'){
lab[i][j] = 1;
}
}
}
queue<obj*> q;
obj *test = new obj(A.first,A.second,"",nullptr);
q.push(test);
vector<vector<int>> seen(n,vector<int>(m,0));
while(!q.empty()){
auto x = q.front();
q.pop();
if(lab[x->i][x->j] == 2){
cout << "YES" << endl;
int total = 0;
vector<string> f;
for(obj* w=x;w->o != nullptr;w=w->o){
total++;
f.push_back(w->s);
}
cout << total << "\n";
for(int i=f.size()-1;i>=0;i--){
cout << f[i];
}
cout << endl;
return 0;
}
if(check(x->i-1,x->j,n,m,lab,seen)){
obj *test = new obj(x->i-1,x->j,"U",x);
q.push(test);
}
if(check(x->i+1,x->j,n,m,lab,seen)){
obj *test = new obj(x->i+1,x->j,"D",x);
q.push(test);
}
if(check(x->i,x->j-1,n,m,lab,seen)){
obj *test = new obj(x->i,x->j-1,"L",x);
q.push(test);
}
if(check(x->i,x->j+1,n,m,lab,seen)){
obj *test = new obj(x->i,x->j+1,"R",x);
q.push(test);
}
}
cout << "NO" << endl;
return 0;
}