rt.
#include<bits/stdc++.h>
using namespace std;
char OvO[1005][1005];
int n,m,t;
struct kkk{
int x,y,f;
};
bool vis[1005][1005][2];
int dx[4]={1,0,-1,0};
int dy[4]={0,1,0,-1};
vector<kkk> op;
int sumt=0;
int dis(kkk a,kkk b){
return abs(a.x-b.x)+abs(a.y-b.y);
}bool check1(int x,int y,int k){
if(OvO[x][y]!='X'&&x>=1&&x<=n&&y>=1&&y<=m&&vis[x][y][k]==0){
return true;
}return false;
}bool check2(kkk a){
for(int i=0;i<2;i++){
if(dis(a,op[i])<=2*sumt){
return false;
}
}return true;
}
queue<kkk> q1;
queue<kkk> q2;
int bfs(){
while(!q1.empty()&&!q2.empty()){
sumt++;
int tot=3;
while(tot--){
int len=q1.size();
while(len--){
kkk u=q1.front();
q1.pop();
if(!check2(kkk{u.x,u.y})){
continue;
}for(int i=0;i<4;i++){
int xx=u.x+dx[i];
int yy=u.y+dy[i];
if(check1(xx,yy,u.f)&&check2(kkk{xx,yy})){
vis[xx][yy][u.f]=1;
if(vis[xx][yy][!u.f]){
return sumt;
}q1.push(kkk{xx,yy,u.f});
}
}
}
}tot=1;
while(tot--){
int len=q2.size();
while(len--){
kkk u=q2.front();
q2.pop();
if(!check2(kkk{u.x,u.y})){
continue;
}for(int i=0;i<4;i++){
int xx=u.x+dx[i];
int yy=u.y+dy[i];
if(check1(xx,yy,u.f)&&check2(kkk{xx,yy})){
vis[xx][yy][u.f]=1;
if(vis[xx][yy][!u.f]){
return sumt;
}q2.push(kkk{xx,yy,u.f});
}
}
}
}
}return -1;
}
void init(){
memset(vis,0,sizeof vis);
while(!q1.empty()){
q1.pop();
}while(!q2.empty()){
q2.pop();
}op.clear();
sumt=0;
}
int main(){
cin>>t;
while(t--){
init();
cin>>n>>m;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
cin>>OvO[i][j];
if(OvO[i][j]=='M'){
q1.push({i,j,0});
vis[i][j][0]=1;
}else if(OvO[i][j]=='G'){
q1.push({i,j,1});
vis[i][j][1]=1;
}else if(OvO[i][j]=='Z'){
op.push_back(kkk{i,j});
}
}
}cout<<bfs()<<"\n";
}
return 0;
}