#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<queue>
using namespace std;
char mat[25][25]; //地图
int qq[20][20]; //标记
int n,m,ans=9999;
bool flag;
int dir[4][2]={0,1,0,-1,1,0,-1,0};
struct node
{
int x,y;
int step;
friend bool operator<(const node&a,const node&b)
{
return a.step>b.step;
}
}s,s1,s2;
int bfs(int x,int y)
{
priority_queue<node>q;
s.x=x;
s.y=y;
s.step=0;
qq[s.x][s.y]=1;
q.push(s);
while(!q.empty())
{
char c;
s1=q.top(); //优先队列用的是top 不是front
q.pop();
for(int i=0;i<4;i++)
{
s2.x=s1.x+dir[i][0];
s2.y=s1.y+dir[i][1];
s2.step=s1.step+1;
//判断条件 点在图内 且可以走过
if(s2.x>=0&&s2.x<n&&s2.y>=0&&s2.y<m&&mat[s2.x][s2.y]!='*'&&qq[s2.x][s2.y]==0)
{
if(mat[s2.x][s2.y]=='|'||mat[s2.x][s2.y]=='-')
{
if(s2.step%2==1) //步数为奇数是楼梯与刚开始时不同 用一个字符保存楼梯
{
if(mat[s2.x][s2.y]=='-') c='|';
else if(mat[s2.x][s2.y]=='|') c='-';
}
else c=mat[s2.x][s2.y];
s2.x+=dir[i][0];
s2.y+=dir[i][1];
if((c=='-'&&dir[i][0]==0)||(c=='|'&&dir[i][1]==0)) //这时楼梯的方向与你走的方向不同 所以要等待一秒
s2.step += 1;
}
if(mat[s2.x][s2.y]=='T')
return s2.step;
qq[s2.x][s2.y]=1;
q.push(s2);
}
}
}
}
int main()
{
int x,y;
while(scanf("%d%d",&n,&m)!=EOF)
{
getchar();
memset(qq,0,sizeof(qq));
flag=false;
for(int i=0;i<n;i++)
{
for(int j=0;j<=m;j++)
{
scanf("%c",&mat[i][j]);
if(mat[i][j]=='S')
{
x=i;
y=j;
}
}
}
int ans=bfs(x,y);
printf("%d\n",ans);
}
return 0;
}
//90行不算多吧=-=