Link to this code: https://cses.fi/paste/a3a5bced8f359dea3de754/
#include <bits/stdc++.h>

int main() {
    using namespace std;
    using ipair   =   pair<int,int>;
    using ivector =     vector<int>;
    using imatrix = vector<ivector>;
    const auto inf = numeric_limits<int>::max();
    const auto valid_move = "DRUL";
    const auto valid_pos = [](int p, int size) { return p > -1 and p < size; };
    const ivector dx = {1,0,-1,0}, dy = {0,1,0,-1};
    int n, m;
    cin >> n >> m;
    vector<string> cell(n);
    imatrix d(n,ivector(m,inf));
    int sx = -1, sy = -1, tx = -1, ty = -1;
    queue<ipair> q;
    for (int x = 0; x < n; ++x) {
        cin >> cell[x];
        for (int y = 0; y < m; ++y)
            switch (cell[x][y]) {
            case 'A':
                sx = x, sy = y, q.emplace(x,y), d[x][y] = 0;
                break;
            case 'B':
                tx = x, ty = y; } }
    imatrix g(n,ivector(m,-1));
    for (int u, v; !q.empty(); q.pop()) {
        const auto [x,y] = q.front();
        for (int z = d[x][y]+1, k = 0; k < 4; ++k)
            if (valid_pos(u = x+dx[k],n) and valid_pos(v = y+dy[k],m))
                if (cell[u][v] != '#' and z < d[u][v]) {
                    if (d[u][v] = z, g[u][v] = k, u != tx or v != ty)
                        q.emplace(u,v); } }
    if (d[tx][ty] == inf)
        cout << "NO";
    else {
        cout << "YES" << endl << d[tx][ty] << endl;
        string path;
        do {
            const int k = g[tx][ty];
            path += valid_move[k], tx -= dx[k], ty -= dy[k]; }
        while (tx != sx or ty != sy);
        reverse(path.begin(),path.end()), cout << path; }
    return 0; }