#include<bits/stdc++.h>
#define rep(i,n)for(int i=0;i<n;i++)
using namespace std;

vector<int>x[2502], y[2502];
int d[2502][2502];
int p;

int main() {
	int w, h;
	while (scanf("%d%d", &w, &h), w) {
		rep(i, 2502) {
			x[i].clear(); y[i].clear();
		}
		p = 1;//s->0,g->p
		int gx, gy;
		rep(i, h) {
			rep(j, w) {
				string s; cin >> s;
				if (s == ".");
				else if (s == "S")
					x[0].push_back(i), y[0].push_back(j);
				else if (s == "G")gx = i, gy = j;
				else {
					int d = stoi(s); p = max(p, d + 1);
					x[d].push_back(i); y[d].push_back(j);
				}
			}
		}
		x[p].push_back(gx); y[p].push_back(gy);
		memset(d, 0x3f, sizeof(d));
		d[0][0] = 0;
		for (int i = 1; i <= p; i++) {
			rep(j, x[i].size()) {
				rep(k, x[i - 1].size()) {
					d[i][j] = min(d[i][j], d[i - 1][k] + abs(x[i - 1][k] - x[i][j]) + abs(y[i - 1][k] - y[i][j]));
				}
			}
		}
		printf("%d\n", d[p][0]);
	}
}