#include <bits/stdc++.h>
using namespace std;
int n, m;
char s[50][55];
vector<int> g[2500], ng[2500];
int par[2500], ra[2500];
int dsuParent(int v) {
  if (par[v] == v) return v;
  return par[v] = dsuParent(par[v]);
}
void dsuMerge(int u, int v) {
  u = dsuParent(u);
  v = dsuParent(v);
  if (u == v) return;
  if (ra[u] < ra[v]) swap(u, v);
  par[v] = u;
  ra[u] += ra[v];
}
void dsuInit(int n) {
  for (int i = 0; i < (int)(n); ++i) par[i] = i, ra[i] = 1;
}
int dist[2500];
queue<int> q;
int main() {
  scanf("%d%d", &n, &m);
  for (int i = 0; i < (int)(n); ++i) scanf("%s", s[i]);
  dsuInit(n * m);
  for (int i = 0; i < (int)(n - 1); ++i)
    for (int j = 0; j < (int)(m); ++j)
      if (s[i][j] == s[i + 1][j]) {
        dsuMerge(i * m + j, (i + 1) * m + j);
      } else {
        g[i * m + j].push_back((i + 1) * m + j);
        g[(i + 1) * m + j].push_back(i * m + j);
      }
  for (int i = 0; i < (int)(n); ++i)
    for (int j = 0; j < (int)(m - 1); ++j)
      if (s[i][j] == s[i][j + 1]) {
        dsuMerge(i * m + j, i * m + j + 1);
      } else {
        g[i * m + j].push_back(i * m + j + 1);
        g[i * m + j + 1].push_back(i * m + j);
      }
  for (int i = 0; i < (int)(n * m); ++i) {
    int ii = dsuParent(i);
    for (int to : g[i]) {
      int jj = dsuParent(to);
      if (jj != ii) {
        ng[ii].push_back(jj);
      }
    }
  }
  int ans = 1234566;
  n *= m;
  for (int i = 0; i < (int)(n); ++i)
    if (dsuParent(i) == i) {
      for (int j = 0; j < (int)(n); ++j) dist[j] = -1;
      dist[i] = 0;
      q.push(i);
      int mx = 0;
      while (!q.empty()) {
        int v = q.front();
        q.pop();
        for (int to : ng[v])
          if (dist[to] == -1) {
            dist[to] = dist[v] + 1;
            mx = max(mx, dist[to]);
            q.push(to);
          }
      }
      int tmp;
      if (s[i / m][i % m] == 'W')
        tmp = 0;
      else
        tmp = 1;
      tmp = (tmp + mx) % 2;
      mx += tmp;
      ans = min(ans, mx);
    }
  printf("%d\n", ans);
  return 0;
}
