#include <bits/stdc++.h>
using namespace std;
struct FAU {
  int cnt;
  vector<int> p;
  vector<int> r;
  FAU(int n) {
    cnt = n;
    p.resize(n, -1);
    r.resize(n, 0);
  }
  int Find(int x) {
    if (p[x] == -1) return x;
    p[x] = Find(p[x]);
    return p[x];
  }
  bool Together(int x, int y) { return (Find(x) == Find(y)); }
  void Union(int x, int y) {
    x = Find(x);
    y = Find(y);
    if (x == y) return;
    cnt--;
    if (r[x] > r[y])
      p[y] = x;
    else
      p[x] = y;
    if (r[x] == r[y]) ++r[y];
    return;
  }
  int Count() { return cnt; }
};
vector<int> BFS(int v, vector<vector<int> > &G) {
  vector<int> dist((int)(G).size(), 1000000001);
  queue<int> Q;
  Q.push(v);
  dist[v] = 0;
  while (!Q.empty()) {
    int q = Q.front();
    Q.pop();
    for (int u : G[q])
      if (dist[u] == 1000000001) {
        dist[u] = dist[q] + 1;
        Q.push(u);
      }
  }
  return dist;
}
int main() {
  ios_base::sync_with_stdio(0);
  int n, m;
  cin >> n >> m;
  vector<vector<int> > G(n * m);
  char C[n][m];
  for (int i = (0); i <= (n - 1); ++i)
    for (int j = (0); j <= (m - 1); ++j) cin >> C[i][j];
  FAU F(n * m);
  int mX[] = {-1, 0, 1, 0}, mY[] = {0, 1, 0, -1};
  for (int i = (0); i <= (n - 1); ++i)
    for (int j = (0); j <= (m - 1); ++j)
      for (int t = (0); t <= (3); ++t) {
        int ni = i + mX[t], nj = j + mY[t];
        if (ni >= 0 && nj >= 0 && ni < n && nj < m && (C[i][j] == C[ni][nj]))
          F.Union(m * i + j, m * ni + nj);
      }
  for (int i = (0); i <= (n - 1); ++i)
    for (int j = (0); j <= (m - 1); ++j)
      for (int t = (0); t <= (3); ++t) {
        int ni = i + mX[t], nj = j + mY[t];
        if (ni >= 0 && nj >= 0 && ni < n && nj < m && (C[i][j] != C[ni][nj])) {
          int u = F.Find(m * i + j), v = F.Find(m * ni + nj);
          G[u].push_back(v);
          G[v].push_back(u);
        }
      }
  int ans = 1000000001;
  for (int i = (0); i <= (n - 1); ++i)
    for (int j = (0); j <= (m - 1); ++j)
      if (F.Find(m * i + j) == m * i + j) {
        vector<int> dist = BFS(m * i + j, G);
        int mx = -1;
        for (int k = (0); k <= ((int)(dist).size() - 1); ++k)
          if (dist[k] != 1000000001)
            if (C[k / m][k % m] == 'B') mx = max(mx, dist[k]);
        ans = min(ans, mx);
      }
  cout << 1 + ans;
  return 0;
}
