#include <bits/stdc++.h>
using namespace std;
ifstream fin("input.txt");
ofstream fout("output.txt");
const long long mod = 1000000000 + 7;
const int maxn = 500 + 10;
const int inf = 1000000000;
int n, m, ans = inf, fn, rang = 1, cl[51][51], dist[51 * 51], rn[51 * 51];
vector<int> v[51 * 51];
int mx[4] = {1, 0, -1, 0};
int my[4] = {0, 1, 0, -1};
char c[51][51];
queue<int> q;
bool mark[51 * 51];
void bfs(int x) {
  int k = rn[x];
  memset(mark, 0, sizeof mark);
  q.push(x);
  dist[x] = 0;
  mark[x] = 1;
  while (!q.empty()) {
    x = q.front();
    q.pop();
    for (int i = 0; i < v[x].size(); i++)
      if (!mark[v[x][i]]) {
        dist[v[x][i]] = dist[x] + 1;
        q.push(v[x][i]);
        mark[v[x][i]] = 1;
      }
  }
  fn = 0;
  for (int i = 1; i < rang; i++) fn = max(fn, dist[i]);
  if (fn % 2 != k) fn++;
  ans = min(ans, fn);
}
void dfs(int x, int y) {
  cl[x][y] = rang;
  for (int i = 0; i < 4; i++) {
    int a = x + mx[i];
    int b = y + my[i];
    if (a >= 1 && a <= n && b >= 1 && b <= m && !cl[a][b] && c[x][y] == c[a][b])
      dfs(a, b);
  }
}
int main() {
  ios::sync_with_stdio(0);
  cin >> n >> m;
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++) cin >> c[i][j];
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++)
      if (!cl[i][j]) {
        dfs(i, j);
        rn[rang] = (c[i][j] == 'B');
        rang++;
      }
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++)
      for (int z = 0; z < 4; z++) {
        int a = i + mx[z];
        int b = j + my[z];
        if (a >= 1 && a <= n && b >= 1 && b <= m && cl[a][b] != cl[i][j]) {
          v[cl[i][j]].push_back(cl[a][b]);
        }
      }
  for (int i = 1; i < rang; i++) bfs(i);
  cout << ans << endl;
  return 0;
}
