#include<bits/stdc++.h>
#define int long long
#define endl "\n"
using namespace std;

const int max_n = 2010;
const int Mod = 1e9+7;
const int inf = 1e18; 
const int lim = 3e3+20;

char a[max_n][max_n];
int dist[max_n][max_n],visited[max_n][max_n];
int v_char[26];
vector<pair<int,int> > adj[26];

pair<int,int> dir[4] = {{-1,0},{1,0},{0,1},{0,-1}};

signed main(){
    ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
	int n,m;cin>>n>>m;
	char a[n][m];

	pair<int,int> s,e;

	for(int i=0;i<n;i++){
		for(int j=0;j<m;j++){
			cin>>a[i][j];
			if(a[i][j]=='S') s={i,j};
			if(a[i][j]=='G') e={i,j};

			if(a[i][j]>='a' && a[i][j]<='z'){
				adj[a[i][j]-'a'].push_back({i,j});
			}
		}
	}

	queue<pair<int,int> > q;
	q.push(s);

	while(q.size()>0){
		pair<int,int> c = q.front();
		q.pop();

		for(int i=0;i<4;i++){
			pair<int,int> t(c.first+dir[i].first,c.second+dir[i].second);

			if(t.first>=0 && t.first<n && t.second>=0 && t.second<m){
				if(!visited[t.first][t.second] && a[t.first][t.second]!='#'){
					q.push(t);
					dist[t.first][t.second]=dist[c.first][c.second]+1;
					visited[t.first][t.second]=1;
				}
			}
		}

		char X = a[c.first][c.second];
		if(X>='a' && X<='z'){
			if(!v_char[X-'a']){
				v_char[X-'a']=1;
				for(pair<int,int> t:adj[X-'a']){
					if(!visited[t.first][t.second] && a[t.first][t.second]!='#'){
						q.push(t);
						dist[t.first][t.second]=dist[c.first][c.second]+1;
						visited[t.first][t.second]=1;
					}
				}
			}
		}
	}

	if(dist[e.first][e.second]==0){
		cout<<-1<<endl;
	}else{
		cout<<dist[e.first][e.second]<<endl;
	}
}
#include <bits/stdc++.h>
#define rep(i,N) for (int i = 0; i < (N); ++i)
#define all(v) v.begin(), v.end()
using namespace std;
using ll = long long;
using P = pair<int, int>;
const int inf{int(1e9)};
int main(void){
  int N;
  string T;
  cin >> N >> T;

  // N == 1 or 2を例外処理
  if (N == 1){
    if (T == "0") cout << 10000000000 << endl;
    else if (T == "1") cout << 20000000000 << endl;
    return 0;
  }
  else if (N == 2){
    if (T == "00") cout << 0 << endl;
    else if (T == "01") cout << 9999999999 << endl;
    else if (T == "10" || T == "11") cout << 10000000000 << endl;
    return 0;
  }
  // 一つ以上含まれるかどうか確かめる
  rep(i,N){
    if (i%3 == 0 && T[i] != T[0] || i%3 == 1 && T[i] != T[1] || i%3 == 2 && T[i] != T[2]){
      cout << 0 << endl;
      return 0;
    }
    else if(T.substr(0,3) != "110" && T.substr(0,3) != "101" && T.substr(0,3) != "011"){
      cout << 0 << endl;
      return 0;
    }
  }
  // ここまできたら一個以上含まれることが保証される
  ll ans;
  if (T.substr(0,3) == "110"){
    ans = (30000000000 - N) / 3;
    ans ++;
  }
  else if (T.substr(0,3) == "101"){
    ans = (30000000000 - (N+1)) / 3;
    ans ++;
  }
  else if (T.substr(0,3) == "011"){
    ans = (30000000000 - (N+2)) / 3;
    ans ++;
  }
  cout << ans << endl;
  return 0;
}
