// O(RC) BFS
#include <cstdio>
#include <vector>
#include <queue>
using namespace std;

int main() {
	int R,C;
	char c;
	scanf(" %d %d\n",&R,&C);
	vector< vector<bool> > V(R); // volne policko
	vector< vector<int> > dist(R); // vzdialenost
	pair<int,int> zac,end;
	for(int i =0; i < R; i++) {
		V[i].resize(C,true);
		dist[i].resize(C,-1);
		for(int j =0; j < C; j++) {
			scanf("%c",&c);
			if(c == 'X') V[i][j] =false;
			if(c == 'T') {
				zac.first =i;
				zac.second =j;}
			if(c == 'M') {
				end.first =i;
				end.second =j;}}
		scanf("\n");}
	int dx[4] ={1,-1,0,0};
	int dy[4] ={0,0,1,-1};	
	queue< pair<int,int> > n;
	n.push(zac);
	dist[zac.first][zac.second] =0;
	while(!n.empty()) {
		if(n.front() == end) break;
		for(int i =0; i < 4; i++) 
			if(V[n.front().first+dx[i]][n.front().second+dy[i]] && dist[n.front().first+dx[i]][n.front().second+dy[i]] == -1) {
				dist[n.front().first+dx[i]][n.front().second+dy[i]] =dist[n.front().first][n.front().second]+1;
				zac.first =n.front().first+dx[i];
				zac.second =n.front().second+dy[i];
				n.push(zac);}
		n.pop();}
	printf("%d\n",dist[end.first][end.second]);
	return 0;}