#include<iostream>
#include<queue>
using namespace std;
struct node {
int x, y, step,c;
};
int n, m, check[2005][2005], check2[2005][2005];
char map[2005][2005];
int dir[4][2] = { 0,1,1,0,0,-1,-1,0 };
int main() {
cin >> n >> m;
queue<node> que;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> map[i][j];
if (map[i][j] == 'S') {
que.push({ i,j,0,0 });
check[i][j] = 1;
}
}
}
while (!que.empty()) {
node temp = que.front();
que.pop();
for (int i = 0; i < 4; i++) {
int x = temp.x + dir[i][0];
int y = temp.y + dir[i][1];
if (map[x][y] == 'T' && temp.c == 1) {
cout << temp.step + 1 << endl;
return 0;
}
if (map[x][y] == 'P' && check2[x][y] == 0) {
check2[x][y] = 1;
que.push({ x,y,temp.step + 1,1 });
}
else if (map[x][y] == '.' || map[x][y] == 'S' || map[x][y] == 'T') {
if (temp.c == 0 && check[x][y] == 0) {
check[x][y] = 1;
que.push({ x,y,temp.step + 1,0 });
}
else if (temp.c == 1 && check2[x][y] == 0) {
check2[x][y] = 1;
que.push({ x,y,temp.step + 1,1 });
}
}
}
}
return 0;
}