#include <bits/stdc++.h>
using namespace std;
#define rep(i, a, b) for(int i = a; i < b; ++i)

int debug = 0;

const int N = 2010, inf = 1e9;
int n, m, ans, dp[N][N];
vector <int> g[26][N];

main() {
    cin >> n >> m;
    rep(i, 1, n + 1) {
        rep(j, 1, n + 1) {
            if (i == j) {
                dp[i][j] = 0;
            } else {
                dp[i][j] = inf;
            }
        }
    }
    rep(i, 0, m) {
        int a, b, c; char cc;
        cin >> a >> b >> cc;
        c = cc - 'a';
        if (debug) {
            cerr << " edge: " <<  a << ' ' << b << ' ' << cc << endl;
        }
        g[c][a].push_back(b);
        g[c][b].push_back(a);
        if (a != b) dp[a][b] = dp[b][a] = 1;
    }
    set <array <int, 3>> d;
    rep(i, 1, n + 1) rep(j, i, n + 1) {
        d.insert({dp[i][j], i, j});
    }
    while (!d.empty()) {
        auto cur = *d.begin();
        d.erase(cur);
        int w = cur[0], a = cur[1], b = cur[2];
        if (debug) cerr << w << ' ' << a << ' ' << b << '\n';
        assert(a <= b);
        if (w == inf) break;
        rep(c, 0, 26) {
            for (int u : g[c][a]) for (int v : g[c][b]) {
                int uu = u, vv = v;
                if (uu > vv) swap(uu, vv);
                if (dp[uu][vv] > w + 2) {
                    d.erase({dp[uu][vv], uu, vv});
                    dp[uu][vv] = w + 2;
                    d.insert({dp[uu][vv], uu, vv});
                }
            }
        }
    }
    if (dp[1][n] == inf) {
        ans = -1;
    } else {
        ans = dp[1][n];
    }
    cout << ans << '\n';
}
#include <bits/stdc++.h>
#define fi first
#define se second
using namespace std;
int st[100][26];
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int n,m,ex,ey; cin >> n >> m;
  char mt[n+1][m+1];
  queue<pair<int,int> >q;
  vector<pair<int,int> >p[26];
  int dst[n+1][m+1];
  memset(dst,-1,sizeof(dst));
  for(int i=0;i<n;++i){
    for(int j=0;j<m;++j){
      cin >> mt[i][j];
      if(mt[i][j]=='S'){
        q.emplace(i,j);
        dst[i][j]=0;
      }
      if(mt[i][j]=='G'){
        ex = i; ey = j;
      }
      if(mt[i][j]>='a'&&mt[i][j]<='z'){
        p[mt[i][j]-'a'].emplace_back(i,j);
      }
    }
  }
  int dx[4]={-1,1,0,0};
  int dy[4]={0,0,-1,1};
  while(!q.empty()){
    int x=q.front().fi;
    int y=q.front().se;
    q.pop();
    for(int i=0;i<4;++i){
      int nx=x+dx[i];
      int ny=y+dy[i];
      if(nx<0||nx>=n||ny<0||ny>=m||mt[nx][ny]=='#')continue;
      if(~dst[nx][ny])continue;
      dst[nx][ny]=dst[x][y]+1;
      q.emplace(nx,ny);
    }
    if(mt[x][y]>='a'&&mt[x][y]<='z'){
      for(auto po : p[mt[x][y]-'a']){
        if(~dst[po.fi][po.se])continue;
        dst[po.fi][po.se]=dst[x][y]+1;
        q.emplace(po.fi,po.se);
      }
      p[mt[x][y]-'a'].clear();
    }
   
  }
 // cerr<<dst;
  cout<<dst[ex][ey]<<"\n";
}