#include<cstdio>
#include<algorithm>
#include<vector>
#include<queue>
#include<string>
#include<iostream>
#include<cmath>
#include<map>
#include<set>
#include<climits>
#include<ctime>
#include<complex>
#include<sstream>
#include<cstring>
using namespace std;
typedef vector<string>vs;
typedef vector<int>vi;
typedef vector<vi>vvi;
typedef vector<double>vd;
typedef pair<int,int>pii;
typedef long long ll;
typedef pair<ll,ll>pll;
typedef vector<ll>vl;
#define rrep(i,x,n) for(int i=(x);i<(n);++i)
#define rep(i,x) rrep(i,0,(x))
#define fi first
#define se second
#define each(i,c) for(__typeof((c).begin()) i=(c).begin();i!=(c).end();++i)
#define all(c) (c).begin(),(c).end()
#define rall(c) (c).rbegin(),(c).rend()
#define pb push_back
#define maxs(a,b) (a)=max(a,b)
#define mins(a,b) (a)=min(a,b)
typedef pair<int,pii>piii;
int dx[]={-1,0,1,0};
int dy[]={0,1,0,-1};

int W,H,N;
char fld[100][100];
int cost[100][100];
int dist[7][7];
vector<pii>pos;

void prp(){
    int dx1[]={-1,0,1,-1},dy1[]={-1,-1,-1,0};
    int dx2[]={1,0,-1,1},dy2[]={1,1,1,0};

    rep(i,H){
        rep(j,W){
            rep(k,4){
                int ty=i+dy1[k],tx=j+dx1[k];
                if(ty<0||tx<0)continue;
                cost[i][j]=max(cost[i][j],cost[ty][tx]-1);
            }
        }
    }

    for(int i=H-1;i>=0;i--){
        for(int j=W-1;j>=0;j--){
            rep(k,4){
                int ty=i+dy2[k],tx=j+dx2[k];
                if(tx>=W||ty>=H)continue;
                cost[i][j]=max(cost[i][j],max(cost[ty][tx]-1,1));
            }
        }
    }
}

void bfs(int s){
    priority_queue<piii,vector<piii>,greater<piii> >Q;
    Q.push(piii(0,pii(pos[s].fi,pos[s].se)));
    int D[100][100];fill_n(*D,10000,1e9);
    while(!Q.empty()){
        piii p=Q.top();Q.pop();
        if(D[p.se.fi][p.se.se]<=p.fi)continue;
        D[p.se.fi][p.se.se]=p.fi;

        rep(i,4){
            int ty=p.se.fi+dy[i],tx=p.se.se+dx[i];
            if(ty<0||ty>=H||tx<0||tx>=W)continue;
            if(cost[ty][tx]==4)continue;
            Q.push(piii(p.fi+cost[p.se.fi][p.se.se],pii(ty,tx)));
        }
    }

    rep(i,N){
        dist[s][i]=D[pos[i].fi][pos[i].se];
    }
}
int main(){
    fill_n(*cost,100*100,1);
    scanf("%d%d",&W,&H);
    rep(i,H)scanf("%s",fld[i]);
    pos.resize(1);
    int sy,sx,gy,gx;
    rep(i,H){
        rep(j,W){
            if(fld[i][j]=='S'){
                sy=i;sx=j;
                pos[0]=pii(i,j);
            }
            else if(fld[i][j]=='G'){
                gy=i;gx=j;
            }
            else if(fld[i][j]=='#')cost[i][j]=4;
            else if(fld[i][j]=='M'){
                pos.pb(pii(i,j));
            }
        }
    }
    pos.pb(pii(gy,gx));

    N=pos.size();

    prp();

    rep(i,N)bfs(i);

    vi perm(N);rep(i,N)perm[i]=i;
    int mi=INT_MAX;
    do{
        int sum=0;
        rep(i,N-1)sum+=dist[perm[i]][perm[i+1]];
        mi=min(mi,sum);

    }while(next_permutation(perm.begin()+1,perm.end()-1));

    printf("%d\n",mi);


}