#include <bits/stdc++.h>
using namespace std;
const int N=35;
int r,c,x1,y1,x2,y2,xt,yt,num=0;
int dist[][4]={{0,1,0,1},{0,-1,0,-1},{1,0,-1,0},{-1,0,1,0}};
bool vis[N][N];
char arr[N][N];
int flag=0;
struct node{
int x1;
int y1;
int x2;
int y2;
};
queue<node>q;
bool in(int a1,int b1,int a2,int b2){
if((a1>=1&&a1<=c)&&(b1>=1&&b1<=r)&&(a2>=1&&a2<=c)&&(b2>=1&&b2<=r)) return 1;
else return 0;
}
int tx1,ty1,tx2,ty2;
void bfs(int a,int b,int c,int d){
node tmp;
vis[a][b]=vis[c][d]=1;
tmp.x1=a; tmp.y1=b; tmp.x2=c; tmp.y2=d;
q.push(tmp);
while(!q.empty()){
node w;
w=q.front(); q.pop();
for(int i=0;i<4;i++){
tx1=w.x1+dist[i][0];
ty1=w.y1+dist[i][1];
tx2=w.x2+dist[i][2];
ty2=w.y2+dist[i][3];
if(in(tx1,ty1,tx2,ty2)&&!vis[tx1][ty1]&&!vis[tx2][ty2]){
if(tx1==xt&&tx2==xt&&ty1==yt&&ty2==yt) {
flag=1;
return;
}
else if(arr[tx1][ty1]=='X'||arr[tx2][ty2]=='X'){
return;
}
else if(arr[tx1][ty1]=='#'&&arr[tx2][ty2]=='.'){
vis[tx1][ty1]=1; vis[tx2][ty2]=1; tx1=w.x1; ty1=w.y1;
}
else if(arr[tx2][ty2]=='#'&&arr[tx1][ty1]=='.'){
vis[tx2][ty2]=1; vis[tx2][ty2]=1; tx2=w.x2; ty2=w.y2;
}
else if(arr[tx1][ty1]=='#'&&arr[tx2][ty2]=='#'){
vis[tx1][ty1]=1; vis[tx2][ty2]=1;
tx1=w.x1; ty1=w.y1;
tx2=w.x2; ty2=w.y2;
}
else if(arr[tx2][ty2]=='.'&&arr[tx1][ty1]=='.'){
vis[tx1][ty1]=1; vis[tx2][ty2]=1;
}
}
}
node tee;
tee.x1=tx1;
tee.x2=tx2;
tee.y1=ty1;
tee.y2=ty2;
q.push(tee);
num++;
}
}
int main() {
cin>>r>>c;
for(int i=1;i<=r;i++){
for(int j=1;j<=c;j++){
cin>>arr[i][j];
if(arr[i][j]=='G'){
x1=i; y1=j;
}
if(arr[i][j]=='M'){
x2=i; y2=j;
}
if(arr[i][j]=='T'){
xt=i; yt=j;
}
}
}
bfs(x1,y1,x2,y2);
if(flag) cout<<num;
else cout<<"no";
return 0;
}