CSES - Shared codeLink to this code:
https://cses.fi/paste/63c6d1d0c49ca7bf284dd5/
#include <bits/stdc++.h>
using namespace std;
#define FIO \
ios_base::sync_with_stdio(0); \
cin.tie(0); \
cout.tie(0)
#define mod 1000000007
#define ff first
#define ss second
#define int long long
#define pb push_back
#define mp make_pair
#define mt make_tuple
#define pii pair<int, int>
#define vi vector<int>
#define mii map<int, int>
#define endl "\n"
/* --------------------------------------------------------------------------------------------------*/
#define ms(arr, v) memset(arr, v, sizeof(arr))
#define asc(i, a, n) for (int i = a; i < n; i++)
#define dsc(i, a, n) for (int i = n - 1; i >= a; i--)
#define all(x) begin(x), end(x)
#define sz(x) (int)(x).size()
/*----------------------------------------------------------------------------------------------------*/
vector< vector<int> > dir = {{0, 1}, {1, 0}, { -1, 0}, {0, -1}};
vector<char> moves = {'R', 'D', 'U', 'L'};
void solve()
{
int n, m;
cin >> n >> m;
char a[n][m];
int sx, sy, ex, ey;
asc(i, 0, n)
{
asc(j, 0, m)
{
cin >> a[i][j];
if (a[i][j] == 'A')
{
sx = i;
sy = j;
a[i][j] = '.';
}
if (a[i][j] == 'B')
{
ex = i;
ey = j;
a[i][j] = '.';
}
}
}
string res = "";
queue<pair<int, int>> q;
q.push({sx, sy});
vector< vector< pair<char, pair<int, int> > > > ds(n, vector< pair<char, pair<int, int> > >( m, { 'N', { -1, -1} } ) );
while (!q.empty())
{
auto curr = q.front();
q.pop();
a[curr.first][curr.second] = '#';
if (curr.first == ex && curr.second == ey)
break;
for (int i = 0; i < 4; i++)
{
int x = curr.first + dir[i][0];
int y = curr.second + dir[i][1];
if (x < 0 || y < 0 || x >= n || y >= m || a[x][y] == '#')
{
continue;
}
q.push({x, y});
ds[x][y] = { moves[i], {curr.first, curr.second} } ;
}
}
if (a[ex][ey] == '.')
{
cout << "NO" << endl;
return;
}
cout << "YES" << endl;
// cout << sx << " " << sy << endl;
while (ex != sx || ey != sy)
{
res += ds[ex][ey].first;
auto t = ds[ex][ey].second;
ex = t.first;
ey = t.second;
}
reverse(res.begin(), res.end());
cout << res.size() << endl;
cout << res << endl;
}
int32_t main()
{
FIO;
// #ifndef ONLINE_JUDGE
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
// #endif
// int t;
// cin >> t;
// while (t--)
solve();
return 0;
}