#include<iostream>
#include<cmath>
#include<algorithm>
#include<map>
#include<vector>
#include<queue>
#include<cassert>
using namespace std;
#define REP(i, b, n) for(int i = b; i<(int)n; i++)
#define rep(i, n) REP(i, 0, n)
const int N = 100;
typedef pair<int,int> pii;
const int inf = (1<<21);
const int LIM = 3000;
int cost[N][N];
int getdist(int y,int x){
  return abs(y)+abs(x);
}

int solve(int r,int c,int sy,int sx,int gy,int gx,vector<pii> *in,int lim){
  rep(i,r)rep(j,c)cost[i][j]=inf;
  cost[sy][sx]=0;
  rep(i,in[1].size()){
    int y=in[1][i].first,x=in[1][i].second;
    cost[y][x]=min(cost[y][x],cost[sy][sx]+getdist(y-sy,x-sx));
    //cout << cost[y][x] <<" " << cost[sy][sx]+getdist(y-sy,x-sx) << endl;
  }
  REP(i,2,lim){
    rep(j,in[i-1].size()){
      int &py=in[i-1][j].first,&px=in[i-1][j].second;
      //cout << py <<" " << px << " " << cost[py][px] << endl;
      rep(k,in[i].size()){
	int &y=in[i][k].first,&x=in[i][k].second;
	cost[y][x]=min(cost[y][x],cost[py][px]+getdist(py-y,px-x));
      }
    }
  }
  return cost[gy][gx];
}

int main(){
  int r,c;
  while(cin>>c>>r && r){
    vector<pii> in[LIM];
    int lim=0,sy,sx,gy,gx;
    rep(i,r){
      rep(j,c){
	string tmp;
	cin>>tmp;
	if (tmp == ".")continue;
	if (tmp == "S"){
	  sy=i;sx=j;
	}else if (tmp == "G"){
	  gy=i;gx=j;
	}else {
	  int val=atoi(tmp.c_str());
	  in[val].push_back(make_pair(i,j));
	  lim=max(lim,val);
	}
      }
    }
    lim++;
    in[lim].push_back(make_pair(gy,gx));
    lim++;
    cout << solve(r,c,sy,sx,gy,gx,in,lim) << endl;
  }
}