#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define int long long
#define maxn 1005
#define mi LLONG_MIN
#define ma LLONG_MAX
#define mod 1000000007
#define pb push_back
#define S second
#define F first
vector<vector<int>> a(maxn, vector<int>(maxn, 0));
int n, m;
int ans = 0;
bool used[maxn][maxn];
vector<int> dx = {1, -1, 0, 0};
vector<int> dy = {0, 0, 1, -1};
void bfs() {
deque<pair<int, pair<int, int>>> q;
q.push_front({1, {0, 0}});
used[0][0] = 1;
while (!q.empty()) {
int x = q.front().S.F, y = q.front().S.S, cnt = q.front().F;
ans = max(ans, cnt);
q.pop_front();
for (int i = 0; i < 4; i++) {
int nx = dx[i] + x, ny = dy[i] + y;
if (nx >= 0 && nx < n && ny >= 0 && ny < m) {
if (used[nx][ny]) continue;
if (a[nx][ny] == a[x][y]) {
q.push_front({cnt, {nx, ny}});
used[nx][ny] = 1;
} else if (a[nx][ny] > 0) {
q.push_back({cnt + 1, {nx, ny}});
used[nx][ny] = 1;
}
}
}
}
}
int32_t main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> n >> m;
vector<pair<int, int>> v;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
char x;
cin >> x;
if (x == 'T') {
a[i][j] = 1;
} else if (x == 'B') {
a[i][j] = 2;
}
}
}
bfs();
cout << ans;
}