#include <bits/stdc++.h>
using namespace std;
int Read() {
  int x = 0, f = 1;
  char ch = getchar();
  while (ch < '0' || ch > '9') {
    if (ch == '-') f = -1;
    ch = getchar();
  }
  while (ch >= '0' && ch <= '9') {
    x = x * 10 + ch - '0';
    ch = getchar();
  }
  return x * f;
}
const int N = 55, M = N * N * 4, INF = 0x3f3f3f3f;
int n, m, ecnt;
int a[N][N];
int to[M], nx[M], wd[M], fir[N * N];
void Ins(int u, int v, int w) {
  to[++ecnt] = v, nx[ecnt] = fir[u], wd[ecnt] = w, fir[u] = ecnt;
}
int pos(int i, int j) { return (i - 1) * m + j; }
int que[7000000], hd, tl, dis[N * N], inq[N * N];
int SPFA(int s) {
  for (int i = 1; i <= n * m; ++i) dis[i] = INF, inq[i] = 0;
  dis[s] = 0, hd = tl = 0, que[tl++] = s, inq[s] = 1;
  while (hd < tl) {
    int u = que[hd++];
    for (int i = fir[u], v; i; i = nx[i])
      if (dis[v = to[i]] > dis[u] + wd[i]) {
        dis[v] = dis[u] + wd[i];
        if (!inq[v]) que[tl++] = v, inq[v] = 1;
      }
    inq[u] = 0;
  }
  int mx = 0;
  for (int i = 1; i <= n; ++i)
    for (int j = 1; j <= m; ++j) mx = max(mx, dis[pos(i, j)] + !a[i][j]);
  return mx;
}
int main() {
  n = Read(), m = Read();
  for (int i = 1; i <= n; ++i) {
    char ch[N];
    scanf("%s", ch + 1);
    for (int j = 1; j <= m; ++j) a[i][j] = ch[j] == 'W';
  }
  for (int i = 1; i <= n - 1; ++i)
    for (int j = 1; j <= m; ++j)
      Ins(pos(i, j), pos(i + 1, j), a[i][j] ^ a[i + 1][j]),
          Ins(pos(i + 1, j), pos(i, j), a[i][j] ^ a[i + 1][j]);
  for (int j = 1; j <= m - 1; ++j)
    for (int i = 1; i <= n; ++i)
      Ins(pos(i, j), pos(i, j + 1), a[i][j] ^ a[i][j + 1]),
          Ins(pos(i, j + 1), pos(i, j), a[i][j] ^ a[i][j + 1]);
  int ans = INF;
  for (int i = 1; i <= n; ++i)
    for (int j = 1; j <= m; ++j) ans = min(ans, SPFA(pos(i, j)));
  printf("%d\n", ans);
  return 0;
}
