w, h = gets.split.map(&:to_i)

a = (1..h).map{ gets.chomp.split("") }
cost = (1..h).map{ [1] * w }

start = goal = nil
targets = []
(0..h-1).each{|i|
	(0..w-1).each{|j|
		start = [i, j] if a[i][j] == 'S'
		goal = [i, j] if a[i][j] == 'G'
		targets << [i, j] if a[i][j] == 'M'
		if a[i][j] == '#'
			([0, i-2].max..[h-1, i+2].min).each{|y|
				([0, j-2].max..[w-1, j+2].min).each{|x|
					c = 4 - [(y-i).abs, (x-j).abs].max
					cost[y][x] = c if c > cost[y][x]
				}
			}
		end
	}
}

require 'set'
class BucketQueue
	def initialize(max)
		@min = 0
		@loop = 0
		@mod = max + 1
		@count = 0
		@buckets = (0..max).map{ Set.new }	
	end

	def add(obj, key)
		@buckets[key % @mod] << obj
		@count += 1
	end

	def del(obj, key)
		@buckets[key % @mod].delete(obj)
		@count -= 1
	end

	def del_min
		while @buckets[@min].empty?
			@min += 1
			if @min == @mod
				@min = 0
				@loop += 1
			end
		end

		min_obj = nil
		@buckets[@min].each{|obj|
			min_obj = obj
			break
		}

		@buckets[@min].delete(min_obj)
		@count -= 1

		[min_obj, @loop * @mod + @min]
	end

	def empty?
		@count == 0
	end
end

def min_dist(start, goals, cost)
	dist = (1..cost.size).map{ [Float::INFINITY] * cost[0].size }

	queue = BucketQueue.new(3)
	queue.add(start, 0)
	until queue.empty? 
		v, key = queue.del_min
		y, x = v
		idx = goals.index(v)

		[[1,0],[-1,0],[0,1],[0,-1]].each{|dy, dx|
			i, j = y + dy, x + dx
			next unless (0..cost.size-1) === i
			next unless (0..cost[0].size-1) === j
			next if cost[i][j] > 3
			
			d = key + cost[y][x]	
			if dist[i][j] == Float::INFINITY
				queue.add([i, j], d)
				dist[i][j] = d
			elsif d < dist[i][j]
				queue.del([i, j], dist[i][j])
				queue.add([i, j], d)
				dist[i][j] = d
			end
		}
	end
	goals.map{|i, j| dist[i][j]}
end
	
first_dist = min_dist(start, targets, cost)
dist = []
targets.each{|t|
	dist << min_dist(t, targets + [goal], cost)
}

p (0..targets.size-1).to_a.permutation(targets.size).map{|perm|
	total_dist = first_dist[perm[0]]
	perm.each_cons(2){|i, j|
		total_dist += dist[i][j]
	}
	total_dist += dist[perm[-1]][-1]
	total_dist
}.min