#include <bits/stdc++.h>
#define r(i,n) for(int i=0;i<n;i++)
using namespace std;
typedef pair<int,int> P;
vector<P>v[100001];
vector<int> dp[10001];
int get(string x){
  int res=0;
  r(i,x.size())res=res*10+(x[i]-'0');
  return res;
}
int dist(P a,P b){
  return abs(a.first-b.first)+abs(a.second-b.second);
}
string s;
int e,w,h;
int main(){
  while(cin>>w>>h,h){
    r(i,100001)v[i].clear();
    r(i,10001)dp[i].clear();
    P t;
    r(i,h)r(j,w){
      cin>>s;
      if(s=="G")t=P(i,j);
      if(s=="S")v[0].push_back(P(i,j));
      if(isdigit(s[0])){
        int x=get(s);
        v[x].push_back(P(i,j));
        dp[x].push_back(1e9);
      }
    }
    r(i,99999)if(v[i].size()==0){
      v[i].push_back(t);
      dp[i].push_back(1e9);
      e=i;
      break;
    }
    dp[0].push_back(0);
    r(i,e)r(j,v[i].size())r(k,v[i+1].size())
      dp[i+1][k]=min(dp[i+1][k],dp[i][j]+dist(v[i][j],v[i+1][k]));
    cout<<dp[e][0]<<endl;
  }
}