#include <bits/stdc++.h>
using namespace std;
template <typename T>
inline void read(T &x) {
  x = 0;
  char c = getchar();
  bool flag = false;
  while (!isdigit(c)) {
    if (c == '-') flag = true;
    c = getchar();
  }
  while (isdigit(c)) {
    x = (x << 1) + (x << 3) + (c ^ 48);
    c = getchar();
  }
  if (flag) x = -x;
}
int n, m, ma, ans = 200000000;
bool flag;
int dx[4] = {1, -1, 0, 0}, dy[4] = {0, 0, 1, -1};
char w[5000][5000];
struct edge {
  int to, nxt, v;
} e[3000000];
int head[5000 * 5000], edge_cnt;
void add(int from, int to, int val) {
  e[++edge_cnt] = (edge){to, head[from], val};
  head[from] = edge_cnt;
}
int num(int x, int y) { return y + (x - 1) * m; }
int dis[5000];
bool vis[5000];
void spfa(int s) {
  queue<int> q;
  for (int i = 1; i <= num(n, m); ++i) dis[i] = 200000000, vis[i] = false;
  q.push(s);
  dis[s] = 0;
  vis[s] = true;
  while (!q.empty()) {
    int x = q.front();
    q.pop();
    vis[x] = false;
    for (int i = head[x]; i; i = e[i].nxt) {
      int y = e[i].to, v = e[i].v;
      if (dis[y] > dis[x] + v) {
        dis[y] = dis[x] + v;
        if (!vis[y]) {
          vis[y] = true;
          q.push(y);
        }
      }
    }
  }
}
int main() {
  read(n), read(m);
  for (int i = 1; i <= n; ++i) scanf("%s", w[i] + 1);
  for (int i = 1; i <= n; ++i) {
    for (int j = 1; j <= m; ++j) {
      if (w[i][j] == 'B') flag = true;
      for (int p = 0; p < 4; ++p) {
        int nx = i + dx[p], ny = j + dy[p];
        if (nx < 1 || ny < 1 || nx > n || ny > m) continue;
        if (w[i][j] != w[nx][ny])
          add(num(i, j), num(nx, ny), 1);
        else
          add(num(i, j), num(nx, ny), 0);
      }
    }
  }
  if (!flag) {
    puts("0");
    return 0;
  }
  for (int i = 1; i <= n; ++i) {
    for (int j = 1; j <= m; ++j) {
      spfa(num(i, j));
      ma = 0;
      for (int u = 1; u <= n; ++u)
        for (int v = 1; v <= m; ++v)
          if (w[u][v] == 'B') ma = max(ma, dis[num(u, v)]);
      ans = min(ans, ma);
    }
  }
  printf("%d", ans + 1);
  return 0;
}
