#include<bits/stdc++.h>
using namespace std;
char arr[501][501];
bool vis[501][501]; // 标记数组
int cnt[501][501]; // 统计步数的数组
int n,m;
int ix[] = {1,-1,0,0}; //偏移数组
int iy[] = {0,0,1,-1};
struct pos{ // (x,y) 坐标
int x,y;
};
pos start,end; // 开始、结束
void bfs(){
queue<pos> q; // 创建队列
q.push(start); // 加入起点
vis[start.x][start.y] = 1; // 起点标记
cnt[start.x][start.y] = 1; // 起点的步数为1
while(!q.empty()){ // 循环到队列为空
pos head = q.front(); // 获取队首
if(head.x==end.x && head.y==end.y){ //终点
break;
}
//访问四个方向
for(int i=0; i<4; i++){
int nx = head.x + ix[i];
int ny = head.y + iy[i];
//(nx,ny) 新的目标点
// 判断这个点是否合法(在数组范围内,没有被访问过,不是墙壁)
if(nx>=1&&nx<=n&&ny>=1&&ny<=m&&vis[nx][ny]==0&&arr[nx][ny]!='X'){
pos temp;
temp.x = nx;
temp.y = ny;
q.push(temp);
vis[nx][ny] = 1; // 标记
cnt[nx][ny] = cnt[head.x][head.y] + 1;
}
}
q.pop(); // 出队
}
}
int main(){
cin >> n >> m;
for(int i=1; i<=n; i++){
for(int j=1; j<=m; j++){
cin >> arr[i][j];
if(arr[i][j]=='T'){ //终点
end.x = i;
end.y = j;
}
if(arr[i][j]=='S'){ //起点
start.x = i;
start.y = j;
}
}
}
bfs();
if(cnt[end.x][end.y]) cout<<cnt[end.x][end.y];
else cout<<-1;
return 0;
}