#include <bits/stdc++.h>
using namespace std;
char MAP[109][109];
bool vis[109][109];
struct node {
int x, y, step;
}l,r;
int dir[4][2] = { {-1,0} ,{0,1},{1,0},{0,-1} };
int main() {
int n, m;
cin >> n >> m;
int sx, sy, tx, ty;
for (int i = 1; i <= n; i++) {
cin >> MAP[i] + 1;
for (int j = 1; j <= m; j++) {
if (MAP[i][j] == 'S') {
sx = i, sy = j;
}
else if (MAP[i][j] == 'T') {
tx = i, ty = j;
}
}
}
queue<node> q;
q.push({ sx,sy,0 });
vis[sx][sy] = 1;
while (q.size()) {
r = q.front();
q.pop();
if (r.x == tx && r.y == ty) {
cout << r.step;
return 0;
}
for (int i = 0; i < 4; i++) {
l.x = r.x + dir[i][0];
l.y = r.y + dir[i][1];
l.step = r.step + 1;
if (l.x >= 1 && l.x <= n && l.y >= 1 && l.y <= m && !vis[l.x][l.y] && MAP[l.x][l.y] != '#') {
vis[l.x][l.y] = 1;
q.push(l);
}
}
}
cout << -1;
return 0;
}