#include <bits/stdc++.h>
int main() {
std::ios::sync_with_stdio(0);
std::cin.tie(0);
int n, m;
std::cin >> n >> m;
std::vector map(n + 2, std::vector<char> (m + 2, '.'));
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
std::cin >> map[i][j];
}
}
std::vector<int> dx = {+ 1, - 1, + 0, + 0};
std::vector<int> dy = {+ 0, + 0, - 1, + 1};
int cnt = 0;
std::vector vis(n + 2, std::vector (m + 2, 0));
std::vector<std::pair<int, int>> Q = { {1, 1} };
for (; !Q.empty(); cnt++) {
std::vector<std::pair<int, int>> cur;
while (!Q.empty()) {
auto [x, y] = Q.back();
Q.pop_back();
if (vis[x][y]) {
continue;
}
vis[x][y] = 1;
for (int it = 0; it < 4; it++) {
int px = x + dx[it];
int py = y + dy[it];
if (map[px][py] != '.' && !vis[px][py]) {
if (map[px][py] != map[x][y]) {
cur.push_back({px, py});
} else {
Q.push_back({px, py});
}
}
}
}
Q = cur;
}
std::cout << cnt << '\n';
return 0;
}