#include <cmath>
#include <queue>
#include <string>
#include <vector>
#include <iostream>
using namespace std;
struct state {
	int x, y, cost;
};
bool operator<(const state& s1, const state& s2) {
	return s1.cost < s2.cost;
}
int dir[] = { 0, 1, 0, -1 };
int W, H, a[109][109], x[9], y[9], cnt, dist[7][7], d[109][109], dp[9][135], popcount[135]; string s[109];
int main() {
	for (int i = 0; i < 7; i++) {
		for (int j = 1 << i; j < 2 << i; j++) {
			popcount[j] = popcount[j - (1 << i)] + 1;
		}
	}
	cin >> W >> H;
	for (int i = 0; i < H; i++) fill(a[i], a[i] + W, 1);
	for (int i = 0; i < H; i++) {
		cin >> s[i];
		for (int j = 0; j < W; j++) {
			if (s[i][j] == 'S') x[0] = i, y[0] = j;
			if (s[i][j] == 'G') x[1] = i, y[1] = j;
			if (s[i][j] == 'M') x[cnt + 2] = i, y[cnt + 2] = j, cnt++;
			if (s[i][j] == '#') {
				for (int dx = -2; dx <= 2; dx++) {
					for (int dy = -2; dy <= 2; dy++) {
						int c = max(abs(dx), abs(dy));
						int tx = i + dx, ty = j + dy;
						if (0 <= tx && tx < H && 0 <= ty && ty < W) {
							int r = 2;
							if (c == 0) r = 999999999;
							if (c == 1) r = 3;
							a[tx][ty] = max(a[tx][ty], r);
						}
					}
				}
			}
		}
	}
	int p = cnt + 2;
	for (int i = 0; i < p; i++) {
		for (int j = 0; j < H; j++) fill(d[j], d[j] + W, 999999999);
		d[x[i]][y[i]] = 0;
		priority_queue<state> que; que.push(state{ x[i], y[i], 0 });
		while (!que.empty()) {
			state u = que.top(); que.pop();
			for (int j = 0; j < 4; j++) {
				int tx = u.x + dir[j], ty = u.y + dir[j ^ 1];
				int cost = d[u.x][u.y] + a[u.x][u.y];
				if (0 <= tx && tx < H && 0 <= ty && ty < W && d[tx][ty] > cost) {
					d[tx][ty] = cost;
					que.push(state{ tx, ty, -cost });
				}
			}
		}
		for (int j = 0; j < p; j++) dist[i][j] = d[x[j]][y[j]];
	}
	for (int i = 0; i < p; i++) fill(dp[i], dp[i] + (1 << p), 999999999);
	dp[0][1] = 0;
	for (int i = 3; i < 1 << p; i += 2) {
		for (int j = 0; j < p; j++) {
			if (!(i & (1 << j))) continue;
			int sub = i - (1 << j);
			for (int k = 0; k < p; k++) {
				if (!(sub & (1 << k))) continue;
				int s = sub - (1 << (k - 1));
				dp[j][i] = min(dp[j][i], dp[k][sub] + dist[k][j]);
			}
		}
	}
	cout << dp[1][(1 << p) - 1] << endl;
	return 0;
}