#include <iostream>
#include <queue>
#include <string>
using namespace std;
int b1,b2,e1,e2,m,n;
int a[101][101]={0},flag[101][101]={0};
struct T{
int x,y,n;
};
queue <T> Q;
bool check(int x,int y)
{
if( !flag[x][y] && a[x][y] == 1)
if(x >= 0 && x < n && y >= 0 && y < m )
return true;
return false;
}
int BFS()
{
int i,ord[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
T head,temp;
head.x=b1;
head.y=b2;
head.n=0;
Q.push(head);
while(!Q.empty())
{
head=Q.front(); //逐层检测,每次从头部第一个检测,即最上层余下的第一个
Q.pop(); //队列从头部(front)出队,将每一层的每一种情况遍历
for(i=0;i<4;i++)
{
temp.x=head.x+ord[i][0];
temp.y=head.y+ord[i][1];
if(check(temp.x,temp.y))
{
temp.n=head.n+1;
flag[temp.x][temp.y]=1;
Q.push(temp); //逐层入队
if( temp.x == e1 && temp.y == e2 )
return temp.n;
}
}
}
return 0;
}
int main()
{
int i,j;
string str;
cin>>n>>m;
for(i=0;i<n;i++)
{
cin>>str;
for(j=0;j<m;j++)
{
if(str[j]=='#') a[i][j]=0;
else if(str[j]=='.') a[i][j]=1;
else if(str[j]=='S') {b1=i;b2=j;a[i][j]=0;}
else if(str[j]=='G') {e1=i;e2=j;a[i][j]=1;}
}
}
cout<<BFS();
return 0;
}