#include <bits/stdc++.h>
using namespace std;
const int N = 55, V = N * N;
int vmax;
char M[N][N];
int n, m, dest[V];
inline int I(int x, int y) { return (x - 1) * m + y; }
struct DSU {
  int f[V];
  int find(int x) { return f[x] == x ? x : (f[x] = find(f[x])); }
  void merge(int x, int y) { f[find(x)] = find(y); }
  void init(int n) {
    for (int i = 1; i <= n; ++i) f[i] = i;
  }
  int operator[](int x) { return find(x); }
} D;
struct graph_t {
  vector<int> e[V];
  int bfs(int x) {
    static int dis[V], que[V * 5];
    int res(0), l(0), r(0);
    fill(dis, dis + vmax + 1, -1);
    for (dis[que[++r] = x] = 0; l < r;) {
      int x = que[++l];
      if (dest[x]) res = max(res, dis[x]);
      for (int y : e[x])
        if (dis[y] == -1) dis[que[++r] = y] = dis[x] + 1;
    }
    return res;
  }
  void link(int s, int t) {
    e[s].push_back(t);
    e[t].push_back(s);
  }
} G;
int main() {
  scanf("%d%d", &n, &m);
  for (int i = 1; i <= n; ++i) scanf("%s", M[i] + 1);
  D.init(vmax = I(n, m));
  for (int i = 1; i <= n; ++i)
    for (int j = 1; j <= m; ++j) {
      if (j != m && M[i][j] == M[i][j + 1]) D.merge(I(i, j), I(i, j + 1));
      if (i != n && M[i][j] == M[i + 1][j]) D.merge(I(i, j), I(i + 1, j));
    }
  for (int i = 1; i <= n; ++i)
    for (int j = 1; j <= m; ++j) {
      if (j != m && M[i][j] != M[i][j + 1]) G.link(D[I(i, j)], D[I(i, j + 1)]);
      if (i != n && M[i][j] != M[i + 1][j]) G.link(D[I(i, j)], D[I(i + 1, j)]);
    }
  int vs = 0;
  for (int i = 1; i <= n; ++i)
    for (int j = 1; j <= m; ++j)
      if (M[i][j] == 'B') dest[I(i, j)] = 1, ++vs;
  if (!vs) {
    printf("0\n");
    return 0;
  }
  int res = n * m;
  for (int i = 1; i <= n; ++i)
    for (int j = 1; j <= m; ++j)
      if (D[I(i, j)] == I(i, j)) res = min(res, G.bfs(I(i, j)) + 1);
  printf("%d\n", res);
  return 0;
}
