#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#define p pair<int,int>
#define P pair<p,int>
using namespace std;

int parse(string a) {
	int b = 0;
	for (char c : a)b = b * 10 + c - 48;
	return b;
}
int main() {
	int a, b;
	while (cin>>b>>a, a | b) {
		p G;
		vector<P>d[20000];
		int MAX = 0;
		for (int e = 0; e < a; e++) {
			for (int g = 0; g < b; g++) {
				string o;
				cin >> o;
				if (o=="S")d[0].push_back(P(p(e,g), 0));
				else if (o=="G")G = p(e, g);
				else if (o!=".") {
					d[parse(o)].push_back(P(p(e, g), 0));
					MAX = max(MAX, parse(o));
				}
			}
		}
		for (int i = 1; i <= MAX; i++) {
			for (int j = 0; j < d[i].size();j++) {
				int MIN = 1 << 29;
				for (int k = 0; k < d[i - 1].size(); k++) {
					MIN = min(MIN, d[i - 1][k].second + abs(d[i][j].first.first- d[i - 1][k].first.first) + abs(d[i][j].first.second - d[i - 1][k].first.second));
				}
				d[i][j].second = MIN;
			}
		}
		int MINCOST = 1 << 29;
		for (P s : d[MAX]) {
			MINCOST = min(MINCOST, s.second + abs(G.first-s.first.first) + abs(G.second-s.first.second));
		}
		cout << MINCOST << endl;
	}
}