Source Code
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;

char s[503][503];
int a = 300000, b = 300000, c = 300000, d = 300000, e = 300000;
int n, m;

void bfs(int x, int y) {
    queue<pair<int, int>>q;
    int vis[502][502] = {};
    //vis[x][y] = 1;
    q.push(make_pair(x, y));
    int g, h;
    while (!q.empty()) {
        g = q.front().first;
        h = q.front().second;
        if (x == 1 && y == 1) {
            if (s[g][h] == 'B') {
                b = min(b, vis[g][h]);
               // b--;
            }
            else if (s[g][h] == 'O') {
                c = min(c, vis[g][h]);
                //b--;
            }
            else if (g == n && h == m) {
                a = min(a, vis[g][h]);
               // a--;
            }
        }
        else {
            if (s[g][h] == 'B') {
                d = min(d, vis[g][h]);
               // d--;
            }
            else if (s[g][h] == 'O') {
                e = min(e, vis[g][h]);
               // e--;
            }
        }
        if (s[g][h] == 'B' || s[g][h] == 'O') {
            q.pop();
            continue;
        }
        if (!vis[g][h + 1] && s[g][h + 1] && s[g][h + 1] != '#') {
            vis[g][h + 1] = vis[g][h] + 1;
            q.push(make_pair(g, h + 1));
        }
        if (!vis[g][h - 1] && s[g][h - 1] && s[g][h - 1] != '#') {
            vis[g][h - 1] = vis[g][h] + 1;
            q.push(make_pair(g, h - 1));
        }
        if (!vis[g + 1][h] && s[g + 1][h] && s[g + 1][h] != '#') {
            vis[g + 1][h] = vis[g][h] + 1;
            q.push(make_pair(g + 1, h));
        }
        if (!vis[g - 1][h] && s[g - 1][h] && s[g - 1][h] != '#') {
            vis[g - 1][h] = vis[g][h] + 1;
            q.push(make_pair(g - 1, h));
        }
        q.pop();
    }
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    int oo = 0, bb = 0;
    cin >> n >> m;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            cin >> s[i][j];
            if (s[i][j] == 'B') {
                bb++;
            }   
            else if (s[i][j] == 'O') {
                oo++;
            }
        }
    }
    cout << s[0][0];
    int ans = 100000000;
    bfs(1, 1);
    bfs(n, m);
    //cout << a << " " << b << " " << c << " " << d << " " << e << endl;
    int poo = 300000, pbb = 300000;
    if (bb && c != 300000 && e != 300000) {
        poo = c + e + 2;
    }
    if (oo && b != 300000 && d != 300000) {
        pbb = b + d + 2;
    }
    ans = min(a, min(min(min(poo, pbb), c + d + 1), b + e + 1));
    if (ans == 300000) {
        ans = -1;
    }
    cout << ans;
    return 0;
}
/*

.....B#
##O...B
...#...
#...O..
#.B....
*/
Copy
Malik Found a Portal Gun lafi-Odeh
GNU G++17
4 ms
1.3 MB
Wrong Answer