#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <cstring>
using namespace std;
int n, m;
char mat[505][505];
queue <int> qx;
queue <int> qy;
int dx[] = {0,  0, 1, 0, -1};
int dy[] = {0, -1, 0, 1,  0};
bool posecen[505][505];
bool ima_put = 0;
void bfs (int x, int y) {
    memset(posecen, 0, sizeof(posecen));
    posecen[x][y] = 1;
    qx.push(x);
    qy.push(y);

    int nextX;
    int nextY;

    while (qx.size()) {
        for (int kuda = 1; kuda <= 4; kuda++) {
            nextX = qx.front() + dx[kuda];
            nextY = qy.front() + dy[kuda];
            if (mat[nextX][nextY] == 'B') {
                ima_put = 1;
                return;
            }
            if (!posecen[nextX][nextY] && mat[nextX][nextY] != 'X') {
                posecen[nextX][nextY] = 1;
                qx.push(nextX);
                qy.push(nextY);
            }
        }
        qx.pop();
        qy.pop();
    }
}
int main () {
    scanf("%d %d", &n, &m);
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            cin >> mat[i][j];
        }
    }
    bfs(1, 1);
    if (ima_put) {
        printf("-1\n");
    }
    return 0;
}