#include <bits/stdc++.h>
using namespace std;
template <class T>
void checkmin(T &t, T x) {
  if (x < t) t = x;
}
template <class T>
void checkmax(T &t, T x) {
  if (x > t) t = x;
}
template <class T>
void _checkmin(T &t, T x) {
  if (t == -1) t = x;
  if (x < t) t = x;
}
template <class T>
void _checkmax(T &t, T x) {
  if (t == -1) t = x;
  if (x > t) t = x;
}
set<int> fo[2500];
int M[50][50];
char V[51][51], color[2500];
int n, m;
bool is_valid(int x, int y) { return (x >= 0 && x < n && y >= 0 && y < m); }
int CN;
void dfs(int x, int y, char col) {
  if (V[x][y] != col) return;
  M[x][y] = CN;
  if (is_valid(x - 1, y) && M[x - 1][y] == 0) dfs(x - 1, y, col);
  if (is_valid(x + 1, y) && M[x + 1][y] == 0) dfs(x + 1, y, col);
  if (is_valid(x, y - 1) && M[x][y - 1] == 0) dfs(x, y - 1, col);
  if (is_valid(x, y + 1) && M[x][y + 1] == 0) dfs(x, y + 1, col);
}
void add_edge(int f, int t) {
  fo[f].insert(t);
  fo[t].insert(f);
}
int lev[2500], cl, ANS = 1E9;
queue<int> Q;
void bfs(int vr) {
  memset(lev, 0, sizeof lev);
  cl = 1;
  while (!Q.empty()) Q.pop();
  Q.push(vr);
  lev[vr] = 1;
  while (!Q.empty()) {
    int V = Q.front();
    Q.pop();
    for (set<int>::iterator it = fo[V].begin(); it != fo[V].end(); ++it) {
      int T = *it;
      if (lev[T] == 0) {
        lev[T] = lev[V] + 1;
        cl = max(cl, lev[T]);
        Q.push(T);
      }
    }
  }
  cl--;
  if (color[vr] == 'B' && cl % 2 == 0) cl++;
  if (color[vr] == 'W' && cl % 2 == 1) cl++;
  ANS = min(ANS, cl);
}
int main() {
  int i, j, k, l;
  scanf("%d%d", &n, &m);
  for (i = 0; i < n; ++i) scanf("%s", &V[i]);
  for (i = 0; i < n; ++i)
    for (j = 0; j < m; ++j)
      if (M[i][j] == 0) {
        ++CN;
        dfs(i, j, V[i][j]);
      }
  for (i = 0; i < n; ++i)
    for (j = 0; j < m; ++j) {
      color[M[i][j]] = V[i][j];
      if (is_valid(i - 1, j) && M[i - 1][j] != M[i][j])
        add_edge(M[i - 1][j], M[i][j]);
      if (is_valid(i + 1, j) && M[i + 1][j] != M[i][j])
        add_edge(M[i + 1][j], M[i][j]);
      if (is_valid(i, j - 1) && M[i][j - 1] != M[i][j])
        add_edge(M[i][j - 1], M[i][j]);
      if (is_valid(i, j + 1) && M[i][j + 1] != M[i][j])
        add_edge(M[i][j + 1], M[i][j]);
    }
  for (i = 1; i <= CN; ++i) bfs(i);
  cout << ANS << '\n';
  return 0;
}
