#include<bits/stdc++.h>
using namespace std;

#define lint long long
#define P pair<int, int>
#define LLP pair<long long, long long>
#define REP(i, x, n) for(int i = (x), i##_len = (int)(n) ; i < i##_len ; ++i)
#define rep(i, n) for(int i = 0, i##_len = (int)(n) ; i < i##_len ; ++i)
#define repr(i, n) for(int i = (int)(n) - 1 ; i >= 0 ; --i)
#define SORT(x) sort((x).begin(), (x).end())
#define SORT_INV(x) sort((x).rbegin(), (x).rend())

const int IINF = 1e9 + 10;
const long long LLINF = (long long)1e18 + 10;
const long long MOD = (long long)1e9 + 7;
const int dx4[] = {1, 0, -1, 0}, dy4[] = {0, 1, 0, -1};
const int dx8[] = {1, 1, 0, -1, -1, -1, 0, 1}, dy8[] = {0, -1, -1, -1, 0, 1, 1, 1};
const double EPS = 1e-8;

#define int long long

int w, h;
vector< vector<string> > s;
vector< vector< P > > v(2500);
int sy, sx, gy, gx;
int maxi;
int memo[2525][2525];

int solve(int i, int j){
    if(i == maxi + 1){
        return 0;
    }
    if(memo[i][j] >= 0){
        return memo[i][j];
    }

    int res = LLINF;
    rep(k, v[i + 1].size()){
        res = min(res, solve(i + 1, k) + abs(v[i][j].first - v[i + 1][k].first) + abs(v[i][j].second - v[i + 1][k].second));
    }
    return memo[i][j] = res;
}

signed main(){
    cin.tie(0);
    ios::sync_with_stdio(false);

    while(cin >> w >> h, w){

        rep(i, 2500){
            v[i].clear();
        }

        maxi = 0;

        fill(memo[0], memo[2525], -1);

        s.resize(h);
        rep(i, h){
            s[i].resize(w);
            rep(j, w){
                cin >> s[i][j];
                if(s[i][j] == "S"){
                    sy = i;
                    sx = j;
                }else if(s[i][j] == "G"){
                    gy = i;
                    gx = j;
                }else if(s[i][j] != "."){
                    int num = 0;
                    for(auto x : s[i][j]){
                        num *= 10;
                        num += x - '0';
                    }
                    maxi = max(maxi, num);
                    v[num].push_back({i, j});
                }
            }
        }

        v[0].push_back({sy, sx});
        v[maxi + 1].push_back({gy, gx});

        int ans = solve(0, 0);
        cout << ans << endl;
        
    }

    return 0;
}
