#include<bits/stdc++.h>
#define ll long long
#define endl '\n'
#define pr(x) pair<x,x>
#define up(i,j,k,l) for(int i=j;i<=k;i+=l)
#define down(i,j,k,l) for(int i=j;i>=k;i-=l)
using namespace std;
const int N=1e3+10;
const int dx[4]={0,1,-1,0},dy[4]={1,0,0,-1};
int h,w;
char a[N][N];
bool f[N][N];
struct node{
int x,y,t,d;
};
queue< node > q;
int sx,sy,ex,ey;
bool check(int x,int y)
{
if(x<1 || y<1 || x>h || y>w || a[x][y]=='#' || f[x][y]==true){
return false;
}
else{
return true;
}
}
void bfs()
{
q.push({sx,sy,-1,0});
f[sx][sy]=true;
int tx,ty,xx,yy,tt,dd;
while(!q.empty()){
xx=q.front().x;
yy=q.front().y;
tt=q.front().t;
dd=q.front().d;
q.pop();
if(xx==ex && yy==ey){
cout<<dd<<endl;
return;
}
up(i,0,3,1){
tx=dx[i]+xx;
ty=dy[i]+yy;
if(check(tx,ty)){
if(tt==1 && (i==0 || i==3)){
continue;
}
if(tt==2 && (i==1 || i==2)){
continue;
}
f[tx][ty]=true;
if((i==0 || i==3)){
q.push({tx,ty,1,dd+1});
}
if((i==1 || i==2)){
q.push({tx,ty,2,dd+1});
}
}
}
}
cout<<-1<<endl;
return;
}
void solve()
{
cin>>h>>w;
up(i,1,h,1){
up(j,1,w,1){
cin>>a[i][j];
if(a[i][j]=='S'){
sx=i;
sy=j;
}
if(a[i][j]=='G'){
ex=i;
ey=j;
}
}
}
bfs();
return;
}
int main()
{
int _=1;
up(i,1,_,1){
solve();
}
return 0;
}