#include <bits/stdc++.h>
using namespace std;
const int N = 4e3 + 5;
int n, m, ans, vis[N][N], dx[] = {0, 0, -1, 1}, dy[] = {1, -1, 0, 0};
char tb[N][N];
queue<pair<int, int>> q;
vector<pair<int, int>> v;
signed main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> n >> m;
for(int i = 1;i<=n;i++) for(int j = 1;j<=m;j++) cin >> tb[i][j];
++ans;
q.push({n, m});
vis[n][m] = 1;
while(q.size()){
auto [x, y] = q.front();
v.push_back({x, y});
q.pop();
for(int i = 0;i<4;i++){
int nx = x + dx[i], ny = y + dy[i];
if(nx >= 1 && nx <= n && ny >= 1 && ny <= m && tb[nx][ny] == tb[n][m] && !vis[nx][ny]){
vis[nx][ny] = 1;
q.push({nx, ny});
}
}
}
while(v.size()){
vector<pair<int, int>> vv;
for(auto [x, y] : v){
for(int i = 0;i<4;i++){
int nx = x + dx[i], ny = y + dy[i];
if(nx >= 1 && nx <= n && ny >= 1 && ny <= m && tb[nx][ny] != '.' && !vis[nx][ny]){
vis[nx][ny] = 1;
vv.push_back({nx, ny});
}
}
}
v = vv;
ans += !v.empty();
}
cout << ans;
}