#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<sstream>
#include<climits>
#include<cstdio>
#include<cstdlib>
using namespace std;

vector<vector<char> > f;
vector<vector<int> > cost;
vector<pair<int,int> > M;
vector<pair<int,int> > hole;
pair<int,int> s,g;
struct S{
  pair<int,int> pos;
  int cost;
  int get;
};
bool operator<(S a,S b){
  return a.cost>b.cost;
}

const int vx[]={0,0,1,-1};
const int vy[]={1,-1,0,0};
bool all(int get){
  return get==(1<<M.size())-1;
}
vector<map<pair<int,int>,int>> dp;
int solve(){
  priority_queue<S> que;
  que.push(S{s,0,0});
  dp.clear();
  dp.resize(1<<M.size());
  while(!que.empty()){
    S now  = que.top();que.pop();
    if(now.pos.first<0 || now.pos.first>=cost.size() || now.pos.second <0 || now.pos.second>= cost[0].size())continue;
    if(dp[now.get][now.pos]==1)continue;
    dp[now.get][now.pos]=1;
    for(int i=0;i<M.size();i++){
      if(M[i]==now.pos){
        now.get = now.get | (1<<i);
      }
    }
    if(all(now.get)&&g==now.pos){
      return now.cost;
    }
    for(int i=0;i<4;i++){
      S tmp = now;
      tmp.pos.first += vx[i];
      tmp.pos.second += vy[i];
      tmp.cost += cost[now.pos.first][now.pos.second];
      que.push(tmp);
    }
  }
  return 0;
}
int main(){
  int n,m;
  while(cin>>n>>m){
    f.clear();cost.clear();M.clear();hole.clear();
    f.resize(m);
    for(int i=0;i<m;i++){
      for(int j=0;j<n;j++){
        char tmp;
        cin>>tmp;
        f[i].push_back(tmp);
      }
    }
    for(int i=0;i<f.size();i++){
      for(int j=0;j<f[i].size();j++){
        if(f[i][j]=='#'){
          hole.push_back(make_pair(i,j));
        }else if(f[i][j]=='M'){
          M.push_back(make_pair(i,j));
        }else if(f[i][j]=='S'){
          s = make_pair(i,j);
        }else if(f[i][j]=='G'){
          g = make_pair(i,j);
        }
      }
    }
    cost.resize(f.size());
    for(int i=0;i<f.size();i++){
      for(int j=0;j<f[i].size();j++){
        int tmp=1;
        for(int k=0;k<hole.size();k++){
          if(i==hole[k].first&&j==hole[k].second){
            tmp = INT_MAX/2;
          }else{
            tmp = max(tmp,max(0,min(4-abs(i-hole[k].first),4-abs(j-hole[k].second))));
          }
        }
        cost[i].push_back(tmp);
      }
    }

    cout<<solve()<<endl;
  }
}