CSES - Shared codeLink to this code:
https://cses.fi/paste/44fef82ae5c0733fb0f9cd/
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
#define ll long long
const ll mod = 1e9 + 7;
// Using a pair<int, int> to handle duplicates in pbds
// typedef tree<pair<ll, int>, null_type, less<pair<ll, int>>, rb_tree_tag, tree_order_statistics_node_update> pbds;
typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds; // find_by_order, order_of_key
vector<pair<char, pair<int, int>>> direction = {
{'D', {1, 0}},
{'U', {-1, 0}},
{'L', {0, -1}},
{'R', {0, 1}}
};
void bfs(vector<vector<char>> &grid, int i, int j, string &path)
{
int n = grid.size(), m = grid[0].size();
queue<pair<pair<int, int>, string>> q;
q.push({{i, j}, ""});
while (!q.empty())
{
auto fr = q.front();
int ii = fr.first.first, jj = fr.first.second;
string currPath = fr.second;
q.pop();
if (grid[ii][jj] == 'B')
{
path = currPath;
return;
}
grid[ii][jj] = '#';
for (auto &dir : direction)
{
int iii = ii + dir.second.first;
int jjj = jj + dir.second.second;
char d = dir.first;
if (iii >= 0 && iii < n && jjj >= 0 && jjj < m && grid[iii][jjj] != '#')
{
q.push({{iii, jjj}, currPath + d});
}
}
}
}
void solve()
{
int n, m;
cin >> n >> m;
vector<vector<char>> grid(n, vector<char>(m));
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
cin >> grid[i][j];
}
string ans;
int ii,jj;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
if (grid[i][j] == 'A')
{
ii=i; jj=j;
break;
}
}
}
bfs(grid,ii,jj,ans);
if (ans.empty())
{
cout << "NO" << endl;
}
else
{
cout << "YES" << endl;
cout << ans.size() << endl;
cout << ans << endl;
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
solve();
}