#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll> P;
const ll MOD = 1000000007;
const int IINF = INT_MAX;
const ll LLINF = LLONG_MAX;
const int MAX_N = int(2e5 + 5);
const double EPS = 1e-8;
const int di[] = {0, 1, 0, -1}, dj[] = {1, 0, -1, 0};
#define REP(i, n) for (int i = 0; i < n; i++)
#define REPR(i, n) for (int i = n; i >= 0; i--)
#define SORT(v) sort((v).begin(), (v).end())
#define ALL(v) (v).begin(), (v).end()

int main() {
    int h, w;
    while(cin >> w >> h, h){
        vector<P> g[10005];
        ll n=0, gi, gj;
        REP(i,h)REP(j,w){
            string s;
            cin >> s;
            if(s=="."){
                continue;
            }
            else if(s=="S")g[0].push_back({i,j});
            else if(s=="G"){
                gi = i;
                gj = j;
            }
            else{
                ll num = stoi(s);
                g[num].push_back({i,j});
                n = max(n,num);
            }
        }
        n++;
        g[n].push_back({gi,gj});
        vector<vector<ll>> dp(n+1);
        REP(i,n+1) dp[i].resize(g[i].size(),LLINF/3);
        dp[0][0] = 0;
        REP(i,n){
            REP(j,g[i].size()){
                REP(k,g[i+1].size()){
                    ll d = abs(g[i][j].first-g[i+1][k].first) + abs(g[i][j].second-g[i+1][k].second);
                    dp[i+1][k] = min(dp[i+1][k],dp[i][j] + d);
                }
            }
        }
        cout << dp[n][0] << endl;
    }
    return 0;
}   

