#pragma GCC target ("avx2")
#pragma GCC optimization ("O3")
#pragma GCC optimization ("unroll-loops")

using namespace std;
#include "bits/stdc++.h"
#define el "\n"

typedef long long ll;
const int MM = 2e3+1, MOD = 1e9+7;
int R, C, dir[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
pair<int, int> st, ed;
vector<pair<int, int>> tele[26];
char gr[MM][MM];
bool vis[MM][MM], used[26];
queue<pair<pair<int, int>, int>> q;

int main() {
    cin.tie(0); cout.tie(0); ios::sync_with_stdio(0);
    cin >> R >> C;
    for(int i = 1; i <= R; i++) {
        for(int j = 1; j <= C; j++) {
            cin >> gr[i][j];
            if(gr[i][j] == 'S') {
                st = {i, j};
            } else if(gr[i][j] == 'G') {
                ed = {i, j};
            } else if(gr[i][j] != '.' && gr[i][j] != '#') {
                tele[gr[i][j] - 'a'].push_back({i, j});
            }
        }
    }
    q.push({st, 0}); vis[st.first][st.second] = true;
    while(!q.empty()) {
        int x = q.front().first.first, y = q.front().first.second, d = q.front().second; q.pop();
        if(x == ed.first && y == ed.second) {
            cout << d << el;
            return 0;
        }
        for(int i = 0; i < 4; i++) {
            int nx = x + dir[i][0], ny = y + dir[i][1];
            if(nx >= 1 && nx <= R && ny >= 1 && ny <= C && vis[nx][ny] == false && gr[nx][ny] != '#') {
                vis[nx][ny] = true;
                q.push({{nx, ny}, d + 1});
            }
        }

        if(gr[x][y] != 'S' && gr[x][y] != 'G' && gr[x][y] != '.' && gr[x][y] != '#') {
            if(used[gr[x][y] - 'a'] == true) continue;
            used[gr[x][y] - 'a'] = true;
            for(pair<int, int> t : tele[gr[x][y] - 'a']) {
                if(t.first == x && t.second == y) continue;
                if(vis[t.first][t.second] == false) {
                    vis[t.first][t.second] = true;
                    q.push({{t.first, t.second}, d + 1});
                }
            }
        }
    }
    cout << -1 <<el;
}

// initialize
#include<cstdio>
using namespace std;
const int N=2010,M=1000000007;
int h,w,dp[N][N],s[N][N],z[N][N],x[N][N];
char c[N][N];
int main(){
	scanf("%d%d",&h,&w);
	for(int i=0;i<h;++i)scanf("%s",c[i]);
	dp[0][0]=1;
	for(int i=0;i<h;++i)for(int j=0;j<w;++j){
		if(i||j)dp[i][j]=((long long)s[i][j]+z[i][j]+x[i][j])%M;
		if(i<h-1&&c[i+1][j]=='.')s[i+1][j]=(s[i][j]+dp[i][j])%M;
		if(j<w-1&&c[i][j+1]=='.')z[i][j+1]=(z[i][j]+dp[i][j])%M;
		if(i<h-1&&j<w-1&&c[i+1][j+1]=='.')x[i+1][j+1]=(x[i][j]+dp[i][j])%M;
	}
	printf("%d",dp[h-1][w-1]);
	return 0;
}