#include <bits/stdc++.h>
using namespace std;
char s[501][501];
int num[501][501];
int x[1000001], y[1000001];
int c[25001];
int a[501][501];
int dx[5], dy[5];
int dist[25001];
bool pd[25001];
char ch;
int i, j, n, m, l, ans, mx, ll, rr;
void bfs(int xx, int yy, int kk) {
  x[1] = xx;
  y[1] = yy;
  num[xx][yy] = kk;
  for (ll = 1, rr = 1; ll <= rr; ll++)
    for (int i = 1; i <= 4; i++)
      if (num[x[ll] + dx[i]][y[ll] + dy[i]] == 0 &&
          s[x[ll] + dx[i]][y[ll] + dy[i]] == s[xx][yy]) {
        num[x[ll] + dx[i]][y[ll] + dy[i]] = kk;
        rr++;
        x[rr] = x[ll] + dx[i];
        y[rr] = y[ll] + dy[i];
      }
}
void spfa(int k) {
  memset(dist, 10, sizeof(dist));
  memset(pd, false, sizeof(pd));
  dist[k] = 0;
  pd[k] = true;
  for (ll = 1, rr = 1, x[ll] = k; ll <= rr; ll++) {
    for (int i = 1; i <= l; i++)
      if (dist[x[ll]] + a[x[ll]][i] < dist[i]) {
        if (pd[i] == false) {
          pd[i] = true;
          rr++;
          x[rr] = i;
        }
        dist[i] = dist[x[ll]] + a[x[ll]][i];
      }
    pd[x[ll]] = false;
  }
  mx = 0;
  for (int i = 1; i <= l; i++) mx = max(mx, dist[i] + c[i]);
  ans = min(ans, mx);
}
int main() {
  scanf("%d%d\n", &n, &m);
  memset(num, 0, sizeof(num));
  dx[1] = 1;
  dx[2] = 0;
  dx[3] = -1;
  dx[4] = 0;
  dy[1] = 0;
  dy[2] = 1;
  dy[3] = 0;
  dy[4] = -1;
  l = 0;
  for (i = 1; i <= n; i++) {
    for (j = 1; j <= m; j++) s[i][j] = getchar();
    ch = getchar();
  }
  for (i = 1; i <= n; i++)
    for (j = 1; j <= m; j++)
      if (num[i][j] == 0) {
        l++;
        if (s[i][j] == 'W')
          c[l] = -1;
        else
          c[l] = 1;
        bfs(i, j, l);
      }
  memset(a, 10, sizeof(a));
  for (i = 1; i <= n; i++)
    for (j = 1; j <= m; j++) {
      if (num[i][j] != num[i - 1][j])
        a[num[i][j]][num[i - 1][j]] = 1, a[num[i - 1][j]][num[i][j]] = 1;
      if (num[i][j] != num[i][j - 1])
        a[num[i][j]][num[i][j - 1]] = 1, a[num[i][j - 1]][num[i][j]] = 1;
    }
  ans = 10000000;
  for (i = 1; i <= l; i++) spfa(i);
  printf("%d\n", ans);
  return 0;
}
