#include <bits/stdc++.h>

using namespace std;

#define LOG(...) fprintf(stderr,__VA_ARGS__)
//#define LOG(...)
#define FOR(i,a,b) for(int i=(int)(a);i<(int)(b);++i)
#define REP(i,n) for(int i=0;i<(int)(n);++i)
#define ALL(a) (a).begin(),(a).end()
#define RALL(a) (a).rbegin(),(a).rend()
#define EXIST(s,e) ((s).find(e)!=(s).end())
#define SORT(c) sort(ALL(c))
#define RSORT(c) sort(RALL(c))

typedef long long ll;
typedef unsigned long long ull;
typedef vector<bool> vb;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector<vb> vvb;
typedef vector<vi> vvi;
typedef vector<vll> vvll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;

#define INF 1e9

int W, H;

int main() {
    while (cin >> W >> H, W|H) {
        vvi field(H, vi(W, -1));
        int goal = 0;
        REP(y, H) REP(x, W) {
            string s;
            cin >> s;
            if (s == ".") {
            } else if (s == "S") {
                field[y][x] = 0;
            } else if (s == "G") {
                field[y][x] = -2;
            } else {
                int n = stoi(s);
                field[y][x] = n;
                goal = max(goal, n);
            }
        }
        goal++;
        vector<vector<pii>> treasure(goal+1);
        REP(y, H) REP(x, W) {
            if (field[y][x] == -2) {
                field[y][x] = goal;
            }
            int n = field[y][x];
            if (n >= 0) {
                treasure[n].push_back({x, y});
            }
        }

        vvi dp(H, vi(W, INF));
        int x = treasure[0][0].first, y = treasure[0][0].second;
        dp[y][x] = 0;
        FOR(i, 1, goal+1) {
            for (pii from : treasure[i-1]) {
                int x1 = from.first, y1 = from.second;
                for (pii to : treasure[i]) {
                    int x2 = to.first, y2 = to.second;
                    int step = abs(x1-x2) + abs(y1-y2);
                    dp[y2][x2] = min(dp[y2][x2], dp[y1][x1] + step);
                }
            }
        }
        int gx = treasure[goal][0].first, gy = treasure[goal][0].second;
        cout << dp[gy][gx] << endl;
    }
}