#include <cmath>
#include <iostream>
using namespace std;
int x[8] = {0, 1, 2, 3, 5, 7, 8, 9};
int n, ok, k;
int main() {
  while (true) {
    ok = 0;
    cin >> n;
    if (!n) {
      break;
    }
    for (int i = 10; i >= 0; i++) {
      k = (n / (int)pow(8, i)) % 8;
      if (k > 0) {
        ok = 1;
      }
      if (ok == 1) {
        cout << x[k];
      }
    }
    cout << endl;
  }
}

#include <cmath>
#include <iostream>
using namespace std;
int x[8] = {0, 1, 2, 3, 5, 7, 8, 9};
int n, ok, k;
int main() {
  while (true) {
    ok = 0;
    cin >> n;
    if (!n) {
      break;
    }
    for (int i = 10; i >= 0; i--) {
      k = (n / (int)pow(8, i)) % 8;
      if (k > 0) {
        ok = 1;
      }
      if (ok == 1) {
        cout << x[k];
      }
    }
    cout << endl;
  }
}


#include <algorithm>
#include <bitset>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <vector>

#define all(c) (c).begin(), (c).end()
#define rep(i, n) for (int i = 0; i < (n); i++)
#define pb(e) push_back(e)
#define mp(a, b) make_pair(a, b)
#define fr first
#define sc second

const int INF = 100000000;
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
using namespace std;
typedef pair<int, int> P;
typedef long long ll;

const int MAX_N = 1000000009;
vector<int> ans;

bool ok(int a) {
  while (a) {
    if (a % 10 == 4 || a % 10 == 6)
      return false;
    a /= 10;
  }
  return true;
}
void init() {
  ans.reserve(MAX_N);
  rep(i, MAX_N) {
    if (!i)
      continue;
    if (ok(i))
      ans.pb(i);
  }
}
int main() {
  init();
  int n;
  while (cin >> n) {
    if (!n)
      break;
    cout << ans[n - 1] << endl;
  }
  return 0;
}

#include <algorithm>
#include <bitset>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <vector>

#define all(c) (c).begin(), (c).end()
#define rep(i, n) for (int i = 0; i < (n); i++)
#define pb(e) push_back(e)
#define mp(a, b) make_pair(a, b)
#define fr first
#define sc second

const int INF = 100000000;
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
using namespace std;
typedef pair<int, int> P;
typedef long long ll;

const int MAX_N = 1e9 + 9;
vector<int> ans;

bool ok(int a) {
  while (a) {
    if (a % 10 == 4 || a % 10 == 6)
      return false;
    a /= 10;
  }
  return true;
}

int n;
string s[] = {"0", "1", "2", "3", "5", "7", "8", "9"};
void hoge() {
  ans.reserve(100000);
  rep(i, 101) {
    if (!i)
      continue;
    if (ok(i))
      ans.pb(i);
    // if(log10(i) == floor(log10(i)))
  }
  cout << endl;
  rep(i, ans.size()) {
    // if((i+1)%8==0)
    cout << i + 1 << " " << ans[i] << endl;
  }
}

int main() {

  while (cin >> n) {
    if (!n)
      break;
    string ans;
    while (n) {
      ans += s[n % 8];
      n >>= 3;
    }
    reverse(all(ans));
    cout << ans << endl;
  }

  return 0;
}

terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc


#include <algorithm>
#include <assert.h>
#include <iostream>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <vector>

using namespace std;
typedef long long ll;
typedef unsigned int uint;
typedef unsigned long long ull;
static const double EPS = 1e-9;
static const double PI = acos(-1.0);

#define REP(i, n) for (int i = 0; i < (int)(n); i++)
#define FOR(i, s, n) for (int i = (s); i < (int)(n); i++)
#define FOREQ(i, s, n) for (int i = (s); i <= (int)(n); i++)
#define FORIT(it, c)                                                           \\
  for (__typeof((c).begin()) it = (c).begin(); it != (c).end(); it++)
#define MEMSET(v, h) memset((v), h, sizeof(v))

ll calc(ll n, int digit) {
  assert(digit != 0);
  ll ret = 0;
  int d = n / digit;
  if (digit == 1) {
    if (d >= 6) {
      ret--;
    }
    if (d >= 4) {
      ret--;
    }
    ret += d + 1;
  } else {
    if (n / digit == 0) {
      return calc(n, digit / 10);
    }
    if (d == 4) {
      ret = 4 * calc(digit - 1, digit / 10);
    } else if (d == 6) {
      ret = 5 * calc(digit - 1, digit / 10);
    } else {
      if (d >= 6) {
        d -= 2;
      } else if (d >= 4) {
        d -= 1;
      }
      ret = d * calc(digit - 1, digit / 10);
      ret += calc(n % digit, digit / 10);
    }
  }
  return ret;
}

int main() {
  ll n;
  while (scanf("%lld", &n), n) {
    ll left = n;
    ll right = 10000000000LL;
    while (left != right) {
      ll mid = (left + right) / 2;
      if (calc(mid, 1000000000) - 1 < n) {
        left = mid + 1;
      } else {
        right = mid;
      }
    }
    printf("%lld\\n", left);
  }
}

#include <algorithm>
#include <assert.h>
#include <iostream>
#include <map>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <vector>

using namespace std;
typedef long long ll;
typedef unsigned int uint;
typedef unsigned long long ull;
static const double EPS = 1e-9;
static const double PI = acos(-1.0);

#define REP(i, n) for (int i = 0; i < (int)(n); i++)
#define FOR(i, s, n) for (int i = (s); i < (int)(n); i++)
#define FOREQ(i, s, n) for (int i = (s); i <= (int)(n); i++)
#define FORIT(it, c)                                                           \\
  for (__typeof((c).begin()) it = (c).begin(); it != (c).end(); it++)
#define MEMSET(v, h) memset((v), h, sizeof(v))

map<ll, ll> memo;
ll calc(ll n, ll digit) {
  if (n == digit * 10 - 1 && memo.count(n)) {
    return memo[n];
  }
  ll ret = 0;
  int d = n / digit;
  if (digit == 1) {
    if (d >= 6) {
      ret--;
    }
    if (d >= 4) {
      ret--;
    }
    ret += d + 1;
  } else {
    if (n / digit == 0) {
      return calc(n, digit / 10);
    }
    if (d == 4) {
      ret = 4 * calc(digit - 1, digit / 10);
    } else if (d == 6) {
      ret = 5 * calc(digit - 1, digit / 10);
    } else {
      if (d >= 6) {
        d -= 2;
      } else if (d >= 4) {
        d -= 1;
      }
      ret = d * calc(digit - 1, digit / 10);
      ret += calc(n % digit, digit / 10);
    }
  }
  if (n == digit * 10 - 1) {
    memo[n] = ret;
  }
  return ret;
}

int main() {
  ll n;
  while (scanf("%lld", &n), n) {
    ll left = n;
    ll right = 10000000000LL;
    while (left != right) {
      ll mid = (left + right) / 2;
      if (calc(mid, 1000000000) - 1 < n) {
        left = mid + 1;
      } else {
        right = mid;
      }
    }
    printf("%lld\\n", left);
  }
}


#include <iostream>
using namespace std;

int main() {
  while (1) {
    int a, j = 0;
    cin >> a;
    j = a;
    string s = "";
    int b = 0;
    for (b = 1; b * 8 <= a; b *= 8) {
    }
    for (int c = b; c != 1; c /= 8) {
      int o = a / c;
      switch (a / c) {
      case 0:
      case 1:
      case 2:
      case 3:
        cout << a / c;
        break;
      case 4:
        cout << 5;
        break;
      default:
        cout << a / c + 2;
        break;
      }

      a -= c * o;
    }
    switch (j % 8) {
    case 0:
    case 1:
    case 2:
    case 3:
      cout << j % 8;
      break;
    case 4:
      cout << 5;
      break;
    default:
      cout << j % 8 + 2;
    }

    cout << endl;
  }
}

#include <iostream>
using namespace std;

int main() {
  while (1) {
    int a, j = 0;
    cin >> a;
    if (a == 0)
      break;
    j = a;
    string s = "";
    int b = 0;
    for (b = 1; b * 8 <= a; b *= 8) {
    }
    for (int c = b; c != 1; c /= 8) {
      int o = a / c;
      switch (a / c) {
      case 0:
      case 1:
      case 2:
      case 3:
        cout << a / c;
        break;
      case 4:
        cout << 5;
        break;
      default:
        cout << a / c + 2;
        break;
      }

      a -= c * o;
    }
    switch (j % 8) {
    case 0:
    case 1:
    case 2:
    case 3:
      cout << j % 8;
      break;
    case 4:
      cout << 5;
      break;
    default:
      cout << j % 8 + 2;
    }

    cout << endl;
  }
}


#include <bits/stdc++.h>
#define INF (1 << 29)
#define all(c) (c).begin(), (c).end()
#define pb(c) push_back(c)
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
typedef pair<int, P> PP;

int getv(int x) {
  if (x = 4)
    return 5;
  return (x < 4) ? x : x + 2;
}

void convert(int n) {
  if (n = 0)
    return;
  convert(n / 8);
  cout << getv(n % 8);
}

int main() {
  ios::sync_with_stdio(false);
  int n;

  while (cin >> n && n) {
    convert(n);
    cout << endl;
  }
}

#include <bits/stdc++.h>
#define INF (1 << 29)
#define all(c) (c).begin(), (c).end()
#define pb(c) push_back(c)
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
typedef pair<int, P> PP;

int getv(int x) {
  if (x == 4)
    return 5;
  return (x < 4) ? x : x + 2;
}

void convert(int n) {
  if (n == 0)
    return;
  convert(n / 8);
  cout << getv(n % 8);
}

int main() {
  ios::sync_with_stdio(false);
  int n;

  while (cin >> n && n) {
    convert(n);
    cout << endl;
  }
}


#include <iostream>

using namespace std;

int main() {
  int n, num[100];
  while (cin >> n, n) {
    int k = -1;
    do {
      num[++k] = n % 8;
      if (num[k] >= 5)
        num[k] += 2;
      else if (num[k] >= 4)
        ++num[k];
    } while (n /= 8);
    for (int i = k; i >= 0; --i)
      cout << num[i];
    cout << endl;
  }
  return 1;
}

#include <iostream>

using namespace std;

int main() {
  int n, num[100];
  while (cin >> n, n) {
    int k = -1;
    do {
      num[++k] = n % 8;
      if (num[k] >= 5)
        num[k] += 2;
      else if (num[k] >= 4)
        ++num[k];
    } while (n /= 8);
    for (int i = k; i >= 0; --i)
      cout << num[i];
    cout << endl;
  }
  return 0;
}


#include <algorithm>
#include <array>
#include <bitset>
#include <cassert>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <unordered_map>
#include <vector>
using namespace std;

#define int long long
using ll = long long;
using ull = unsigned long long;
using pii = pair<int, int>;

#define rep(i, a, b) for (int i = (a); i < (b); i++)
#define rrep(i, a, b) for (int i = (b)-1; i >= (a); i--)
#define all(a) (a).begin(), (a).end()
#define dump(o)                                                                \\
  { cerr << #o << " " << o << endl; }
#define dumpc(o)                                                               \\
  {                                                                            \\
    cerr << #o;                                                                \\
    for (auto &e : (o))                                                        \\
      cerr << " " << e;                                                        \\
    cerr << endl;                                                              \\
  }
#define INF 0x3f3f3f3f
#define INFL 0x3f3f3f3f3f3f3f3fLL

signed main() {
  // i?????? S????????? 4or6????????????
  int dp[12][2][2] = {};
  unordered_map<int, int> m;
  for (string S; cin >> S && S != "0";) {
    string prev = "-1";
    m[stoll(prev)] = 0;
    while (prev != S) {
      memset(dp, 0, sizeof(dp));
      dp[0][0][0] = 1;
      rep(i, 0, S.size()) rep(j, 0, 2) rep(k, 0, 2) {
        int lim = j ? 9 : S[i] - '0';
        rep(d, 0, lim + 1) {
          //?????§??????????¢??????????????????????????¢????
          (dp[i + 1][j || d < lim][k || d == 4 || d == 6] += dp[i][j][k]);
        }
      }
      int s = m[stoll(prev)];
      prev = S;
      m[stoll(S)] = dp[S.size()][0][1] + dp[S.size()][1][1];
      S = to_string(stoll(S) + m[stoll(S)] - s);
      // dump(S);
    }
    cout << S << endl;
  }
  return 0;
}

#include <algorithm>
#include <array>
#include <bitset>
#include <cassert>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <unordered_map>
#include <vector>
using namespace std;

#define int long long
using ll = long long;
using ull = unsigned long long;
using pii = pair<int, int>;

#define rep(i, a, b) for (int i = (a); i < (b); i++)
#define rrep(i, a, b) for (int i = (b)-1; i >= (a); i--)
#define all(a) (a).begin(), (a).end()
#define dump(o)                                                                \\
  { cerr << #o << " " << o << endl; }
#define dumpc(o)                                                               \\
  {                                                                            \\
    cerr << #o;                                                                \\
    for (auto &e : (o))                                                        \\
      cerr << " " << e;                                                        \\
    cerr << endl;                                                              \\
  }
#define INF 0x3f3f3f3f
#define INFL 0x3f3f3f3f3f3f3f3fLL

// n??????
// Radix r;
// cout << r.to(n, 4) << endl;
class Radix {
private:
  const char *s;
  int a[128];

public:
  Radix(const char *s = "0123456789ABCDEF") : s(s) {
    for (int i = 0; s[i]; i++)
      a[(int)s[i]] = i;
  }
  string to(long long p, int q) {
    if (!p)
      return "0";
    char t[64] = {};
    int i;
    for (i = 62; p; i--) {
      t[i] = s[p % q];
      p /= q;
    }
    return string(t + i + 1);
  }
  string to(const string &t, int p, int q) { return to(to(t, p), q); }
  long long to(const string &t, int p) {
    long long sm = a[(int)t[0]];
    for (int i = 1; i < (int)t.length(); i++)
      sm = sm * p + a[(int)t[i]];
    return sm;
  }
};

signed main() {
  for (int n; cin >> n && n;) {
    Radix r("01235789");
    cout << r.to(n, 8) << endl;
  }
  return 0;
}


#include <algorithm>
#include <cmath>
#include <iostream>
#include <map>
#include <vector>

using namespace std;

typedef long long ll;

int fourOrSixPlace(ll num) {
  int idx = -1;
  int cnt = 0;
  while (num > 0) {
    if (num % 10 == 6 || num % 10 == 4) {
      idx = cnt;
    }
    num /= 10;
    cnt++;
  }
  return idx;
}

int main() {

  // int cc=0;
  // for(ll i = 1; i <= 100000; i++){
  //	int ret=fourOrSixPlace(i);
  //	if(ret!=-1)
  //		cc++;
  // }
  // cout<<cc<<endl;
  ll n;
  while (cin >> n && n != 0) {
    ll cnum = 0;
    ll cnt = 0;
    while (1) {
      if (cnum > 10000000000LL) {
        return 0;
      }
      cnum += 100000;
      if (cnum > n)
        break;
      int ret = fourOrSixPlace(cnum);
      if (ret == -1) {
        n += 67232;
      } else {
        n += 67232;
        cnum += (ll)pow(10.0, ret);
        n += (ll)pow(10.0, ret);
      }
    }

    if (true) {
      cnum -= 100000;
      cnum++;
      for (ll i = cnum; i <= n; i++) {
        int ret = fourOrSixPlace(i);
        if (ret != -1) {
          if (ret == 0) {
            n++;
          } else {
            n += (ll)pow(10.0, ret);
            i += (ll)pow(10.0, ret);
          }
        }
      }
    }
    cout << n << endl;
  }

  return 0;
}

#include <algorithm>
#include <cmath>
#include <iostream>
#include <map>
#include <vector>

using namespace std;

typedef long long ll;

int cnv(int n) {
  if (n <= 3)
    return n;
  else {
    if (n == 4)
      return 5;
    else
      return n + 2;
  }
}

void dfs(int num) {
  if (num == 0)
    return;
  dfs(num / 8);
  cout << cnv(num % 8);
}

int main() {

  int n;
  while (cin >> n && n != 0) {
    dfs(n);
    cout << endl;
  }

  return 0;
}

// int fourOrSixPlace(ll num){
//	int idx=-1;
//	int cnt=0;
//	while(num>0){
//		if(num%10==6||num%10==4){
//			idx=cnt;
//		}
//		num/=10;
//		cnt++;
//	}
//	return idx;
// }
//
// int main(){
//
//	//int cc=0;
//	//for(ll i = 1; i <= 100000; i++){
//	//	int ret=fourOrSixPlace(i);
//	//	if(ret!=-1)
//	//		cc++;
//	//}
//	//cout<<cc<<endl;
//	ll n;
//	while(cin>>n&&n!=0){
//		ll cnum=0;
//		ll cnt=0;
//		while(1){
//
//			cnum+=100000;
//			if(cnum>n)
//				break;
//			int ret=fourOrSixPlace(cnum);
//			if(ret==-1){
//				n+=67232;
//			}
//			else{
//				n+=67232;
//				cnum+=(ll)pow(10.0,ret);
//				n+=(ll)pow(10.0,ret);
//			}
//		}
//
//		if(true){
//			cnum-=100000;
//			cnum++;
//
//			for(ll i = cnum; i <= n; i++){
//				int ret=fourOrSixPlace(i);
//				if(ret!=-1){
//					if(ret==0){
//						n++;
//					}
//					else{
//						n+=(ll)pow(10.0,ret);
//						i+=(ll)pow(10.0,ret);
//					}
//				}
//			}
//		}
//		cout<<n<<endl;
//	}
//
//
//	return 0;
// }


#include <cstring>
#include <iostream>
#include <string>

using namespace std;

int main() {

  long long int n, r;
  string s = "";
  char x[sizeof(int)];

  while (cin >> n) {
    if (!n)
      break;
    r = 0;

    for (int i = 0; i < n; i++) {
      while (1) {
        r++;
        sprintf(x, "%d", r);
        if (!(strchr(x, '4') != NULL) && !(strchr(x, '6') != NULL))
          break;
      }
    }
    cout << x << endl;
  }

  return 0;
}

#include <iostream>

using namespace std;

int t[8] = {0, 1, 2, 3, 5, 7, 8, 9};

void solve(int);

int main() {

  int n;

  while (cin >> n) {
    if (!n) {
      break;
    }
    solve(n);
    cout << endl;
  }

  return 0;
}

void solve(int n) {

  if (n >= 8) {
    solve(n / 8);
  }

  cout << t[n % 8];
}


#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main() {
  while (1) {
    int n, ans = 0;
    cin >> n;
    if (n == 0)
      break;
    for (int i = 0; i < n; i++) {
      ans++;
      stringstream ss;
      ss << ans;
      string buf = ss.str();
      while (buf.find('4') != string::npos || buf.find('6') != string::npos) {
        ans++;
        ss.str("");
        ss << ans;
        buf = ss.str();
      }
    }
    cout << ans << endl;
  }
  return 0;
}

#include <stdio.h>
int main() {
  int nums[] = {0, 1, 2, 3, 5, 7, 8, 9};
  while (1) {
    int n;
    long long a = 0, d = 1;
    scanf("%d", &n);
    if (!n)
      break;
    while (n) {
      a += nums[n % 8] * d;
      d *= 10;
      n /= 8;
    }
    printf("%lld\\n", a);
  }
  return 0;
}


#include <cstdio>
#include <cstring>
#include <queue>
#include <utility>
using namespace std;

#define INF 10000000

typedef pair<int, int> P;

queue<P> que;
char map[1000][1001];
int vst[1000][1000];
int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};
int H, W, N, sx, sy, sum = 0;

int main() {
  scanf("%d %d %d", &H, &W, &N);
  for (int i = 0; i < H; i++) {
    scanf("%s", map[i]);
    char *ptr = strchr(map[i], 'S');
    if (ptr != NULL)
      sx = ptr - map[i], sy = i;
  }
  que.push(P(sx, sy));
  for (int i = 1; i <= N; i++) {
    for (int j = 0; j < H; j++) {
      for (int k = 0; k < W; k++) {
        vst[j][k] = INF;
      }
    }
    vst[sy][sx] = 0;
    while (!que.empty()) {
      P p = que.front();
      que.pop();
      if (map[p.second][p.first] == i + '0') {
        sum += vst[p.second][p.first];
        while (!que.empty())
          que.pop();
        que.push(P(p.first, p.second));
        sx = p.first, sy = p.second;
        break;
      }
      for (int j = 0; j < 4; j++) {
        int nx = p.first + dx[j], ny = p.second + dy[j];
        if (map[ny][nx] != 'X' && vst[ny][nx] == INF) {
          vst[ny][nx] = vst[p.second][p.first] + 1;
          que.push(P(nx, ny));
        }
      }
    }
  }
  printf("%d\\n", sum);
  return 0;
}

#include <cstdio>
#include <cstring>
#include <queue>
#include <utility>
using namespace std;

#define INF 10000000

typedef pair<int, int> P;

queue<P> que;
char map[1000][1001];
int vst[1000][1000];
int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};
int H, W, N, sx, sy, sum = 0;

int main() {
  scanf("%d %d %d", &H, &W, &N);
  for (int i = 0; i < H; i++) {
    scanf("%s", map[i]);
    char *ptr = strchr(map[i], 'S');
    if (ptr != NULL)
      sx = ptr - map[i], sy = i;
  }
  que.push(P(sx, sy));
  for (int i = 1; i <= N; i++) {
    for (int j = 0; j < H; j++) {
      for (int k = 0; k < W; k++) {
        vst[j][k] = INF;
      }
    }
    vst[sy][sx] = 0;
    while (!que.empty()) {
      P p = que.front();
      que.pop();
      if (map[p.second][p.first] == i + '0') {
        sum += vst[p.second][p.first];
        while (!que.empty())
          que.pop();
        que.push(P(p.first, p.second));
        sx = p.first, sy = p.second;
        break;
      }
      for (int j = 0; j < 4; j++) {
        int nx = p.first + dx[j], ny = p.second + dy[j];
        if (0 <= nx && nx < W && 0 <= ny && ny < H && map[ny][nx] != 'X' &&
            vst[ny][nx] == INF) {
          vst[ny][nx] = vst[p.second][p.first] + 1;
          que.push(P(nx, ny));
        }
      }
    }
  }
  printf("%d\\n", sum);
  return 0;
}


#include <algorithm>
#include <cstring>
#include <iostream>
#include <queue>
using namespace std;
#define MAX 1005

char JOI[MAX][MAX];
int h, w, n;
int dx[] = {0, -1, 0, 1};
int dy[] = {1, 0, -1, 0};

pair<int, int> goal[10];
bool check(int a, int b) { return (a >= 1 && a <= h && b >= 1 && b <= w); }

int step[MAX][MAX];
int bfs(pair<int, int> st, pair<int, int> en) {
  queue<pair<int, int>> q;
  q.push(st);
  memset(step, -1, sizeof(step));
  step[st.first][st.second] = 0;
  int stp = 0;
  while (!q.empty()) {
    pair<int, int> S = q.front();
    q.pop();
    int x = S.first;
    int y = S.second;
    stp = step[x][y];
    for (int i = 0; i < 4; i++) {
      int cx = x + dx[i];
      int cy = y + dy[i];
      if (check(cx, cy)) {
        if (JOI[cx][cy] != 'X') {
          if (cx == en.first && cy == en.second)
            return stp + 1;
          q.push(make_pair(cx, cy));
          step[cx][cy] = stp + 1;
        }
      }
    }
  }
}
int main() {
  cin >> h >> w >> n;
  for (int i = 1; i <= h; i++) {
    for (int j = 1; j <= w; j++) {
      cin >> JOI[i][j];
      if (JOI[i][j] == 'S')
        goal[0] = make_pair(i, j);
      else if (JOI[i][j] >= '0' && JOI[i][j] <= '9') {
        int x = JOI[i][j] - '0';
        goal[x] = make_pair(i, j);
      }
    }
  }
  int ans = 0;
  for (int i = 0; i < n; i++) {
    ans += bfs(goal[i], goal[i + 1]);
  }
  cout << ans << endl;
}

#include <algorithm>
#include <cstring>
#include <iostream>
#include <queue>
using namespace std;
#define MAX 1005

char JOI[MAX][MAX];
int h, w, n;
int dx[] = {0, -1, 0, 1};
int dy[] = {1, 0, -1, 0};

pair<int, int> goal[10];
bool check(int a, int b) { return (a >= 1 && a <= h && b >= 1 && b <= w); }

int step[MAX][MAX];
int bfs(pair<int, int> st, pair<int, int> en) {
  queue<pair<int, int>> q;
  q.push(st);
  memset(step, -1, sizeof(step));
  step[st.first][st.second] = 0;
  int stp = 0;
  while (!q.empty()) {
    pair<int, int> S = q.front();
    q.pop();
    int x = S.first;
    int y = S.second;
    stp = step[x][y];
    for (int i = 0; i < 4; i++) {
      int cx = x + dx[i];
      int cy = y + dy[i];
      if (check(cx, cy)) {
        if (JOI[cx][cy] != 'X' && step[cx][cy] == -1) {
          if (cx == en.first && cy == en.second)
            return stp + 1;
          q.push(make_pair(cx, cy));
          step[cx][cy] = stp + 1;
        }
      }
    }
  }
  return stp;
}
int main() {
  cin >> h >> w >> n;
  for (int i = 1; i <= h; i++) {
    for (int j = 1; j <= w; j++) {
      cin >> JOI[i][j];
      if (JOI[i][j] == 'S')
        goal[0] = make_pair(i, j);
      else if (JOI[i][j] >= '0' && JOI[i][j] <= '9') {
        int x = JOI[i][j] - '0';
        goal[x] = make_pair(i, j);
      }
    }
  }
  int ans = 0;
  for (int i = 0; i < n; i++) {
    ans += bfs(goal[i], goal[i + 1]);
  }
  cout << ans << endl;
}


#include <cstdio>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int xs[10], ys[10];
int H, W, N;
string S[1002];
int main() {
  scanf("%d%d%d", &H, &W, &N);
  for (int i = 0; i < W + 2; i++) {
    S[0] += 'X';
    S[H + 1] += 'X';
  }
  for (int i = 1; i <= H; i++) {
    string x;
    cin >> x;
    S[i] += 'X' + x + 'X';
  }
  for (int i = 1; i <= H; i++) {
    for (int j = 1; j <= W; j++) {
      if (S[i][j] != 'X' && S[i][j] != '.') {
        if (S[i][j] == 'S') {
          xs[0] = j;
          ys[0] = i;
        } else {
          xs[S[i][j] - '0'] = j;
          ys[S[i][j] - '0'] = i;
        }
      }
    }
  }
  int XX[102][102];
  bool FF[102][102];
  int ans = 0;
  vector<pair<int, int>> vec1;
  vector<pair<int, int>> vec2;
  int dx[4] = {-1, 0, 0, 1};
  int dy[4] = {0, -1, 1, 0};
  for (int x = 0; x < N; x++) {
    vec1.clear();
    vec2.clear();
    for (int i = 0; i < H + 2; i++)
      for (int j = 0; j < W + 2; j++) {
        XX[i][j] = -1;
        FF[i][j] = false;
      }
    int cou = 0;
    XX[ys[x]][xs[x]] = cou;
    FF[ys[x]][xs[x]] = true;
    vec1.push_back(make_pair(ys[x], xs[x]));
    while (XX[ys[x + 1]][xs[x + 1]] == -1) {
      vec2.clear();
      for (int i = 0; i < vec1.size(); i++) {
        for (int j = 0; j < 4; j++) {
          if (S[vec1[i].first + dy[j]][vec1[i].second + dx[j]] == 'X')
            continue;
          if (XX[vec1[i].first + dy[j]][vec1[i].second + dx[j]] != -1)
            continue;
          if (FF[vec1[i].first + dy[j]][vec1[i].second + dx[j]])
            continue;
          vec2.push_back(
              make_pair(vec1[i].first + dy[j], vec1[i].second + dx[j]));
          FF[vec1[i].first + dy[j]][vec1[i].second + dx[j]] = true;
        }
      }
      vec1.clear();
      for (int i = 0; i < vec2.size(); i++)
        vec1.push_back(vec2[i]);
      cou++;
      for (int i = 0; i < vec1.size(); i++) {
        XX[vec1[i].first][vec1[i].second] = cou;
      }
    }
    ans += XX[ys[x + 1]][xs[x + 1]];
  }
  printf("%d\\n", ans);
  return 0;
}

#include <cstdio>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int xs[10], ys[10];
int H, W, N;
string S[1002];
int main() {
  scanf("%d%d%d", &H, &W, &N);
  for (int i = 0; i < W + 2; i++) {
    S[0] += 'X';
    S[H + 1] += 'X';
  }
  for (int i = 1; i <= H; i++) {
    string x;
    cin >> x;
    S[i] += 'X' + x + 'X';
  }
  for (int i = 1; i <= H; i++) {
    for (int j = 1; j <= W; j++) {
      if (S[i][j] != 'X' && S[i][j] != '.') {
        if (S[i][j] == 'S') {
          xs[0] = j;
          ys[0] = i;
        } else {
          xs[S[i][j] - '0'] = j;
          ys[S[i][j] - '0'] = i;
        }
      }
    }
  }
  int XX[1002][1002];
  bool FF[1002][1002];
  int ans = 0;
  vector<pair<int, int>> vec1;
  vector<pair<int, int>> vec2;
  int dx[4] = {-1, 0, 0, 1};
  int dy[4] = {0, -1, 1, 0};
  for (int x = 0; x < N; x++) {
    vec1.clear();
    vec2.clear();
    for (int i = 0; i < H + 2; i++)
      for (int j = 0; j < W + 2; j++) {
        XX[i][j] = -1;
        FF[i][j] = false;
      }
    int cou = 0;
    XX[ys[x]][xs[x]] = cou;
    FF[ys[x]][xs[x]] = true;
    vec1.push_back(make_pair(ys[x], xs[x]));
    while (XX[ys[x + 1]][xs[x + 1]] == -1) {
      vec2.clear();
      for (int i = 0; i < vec1.size(); i++) {
        for (int j = 0; j < 4; j++) {
          if (S[vec1[i].first + dy[j]][vec1[i].second + dx[j]] == 'X')
            continue;
          if (XX[vec1[i].first + dy[j]][vec1[i].second + dx[j]] != -1)
            continue;
          if (FF[vec1[i].first + dy[j]][vec1[i].second + dx[j]])
            continue;
          vec2.push_back(
              make_pair(vec1[i].first + dy[j], vec1[i].second + dx[j]));
          FF[vec1[i].first + dy[j]][vec1[i].second + dx[j]] = true;
        }
      }
      vec1.clear();
      for (int i = 0; i < vec2.size(); i++)
        vec1.push_back(vec2[i]);
      cou++;
      for (int i = 0; i < vec1.size(); i++) {
        XX[vec1[i].first][vec1[i].second] = cou;
      }
    }
    ans += XX[ys[x + 1]][xs[x + 1]];
  }
  printf("%d\\n", ans);
  return 0;
}


#include <iostream>
#include <queue>
using namespace std;

int h, w, n;
char map[1000][1000];
struct P {
  int t, i, j;
  P() {
    t = 0;
    i = 0;
    j = 0;
  };
  P(int time, int x, int y) {
    t = time;
    i = x;
    j = y;
  };
};
int cal(int a, int b) {
  char start = a == 0 ? 'S' : '0' + a;
  bool flags[1000][1000];
  int si, sj;
  for (int i = 0; i < h; i++)
    for (int j = 0; j < w; j++) {
      flags[i][j] = false;
      if (map[i][j] == start) {
        si = i;
        sj = j;
      }
    }

  int dx[] = {0, 0, 1, -1}, dy[] = {1, -1, 0, 0};

  queue<P> q;
  q.push(P(0, si, sj));
  while (!q.empty()) {
    P p = q.front();
    q.pop();
    if (p.i < 0 || p.j < 0)
      continue;
    if (p.i >= h || p.j >= w)
      continue;

    //    if( flags[p.i][p.j] ) continue;
    flags[p.i][p.j] = true;

    if (map[p.i][p.j] == '0' + b)
      return p.t;
    if (map[p.i][p.j] == 'X')
      continue;

    p.t++;
    for (int d = 0; d < 4; d++) {
      int ni = p.i + dx[d], nj = p.j + dy[d];
      if (flags[ni][nj])
        continue;
      q.push(P(p.t, ni, nj));
    }
  }

  return -1;
}

int main() {
  cin >> h >> w >> n;
  for (int i = 0; i < h; i++)
    for (int j = 0; j < w; j++)
      cin >> map[i][j];

  int time = 0, r;
  for (int i = 0; i < n; i++) {
    r = cal(i, i + 1);
    time += r;
    //    cout << i << " => " << (i+1) << "\\t | " << r << endl;
  }
  cout << time << endl;

  return 0;
}

#include <iostream>
#include <queue>
using namespace std;

int h, w, n;
char map[1000][1000];
struct P {
  int t, i, j;
  P() {
    t = 0;
    i = 0;
    j = 0;
  };
  P(int time, int x, int y) {
    t = time;
    i = x;
    j = y;
  };
};
int cal(int a, int b) {
  char start = a == 0 ? 'S' : '0' + a;
  bool flags[1000][1000];
  int si, sj;
  for (int i = 0; i < h; i++)
    for (int j = 0; j < w; j++) {
      flags[i][j] = false;
      if (map[i][j] == start) {
        si = i;
        sj = j;
      }
    }

  int dx[] = {0, 0, 1, -1}, dy[] = {1, -1, 0, 0};

  queue<P> q;
  q.push(P(0, si, sj));
  while (!q.empty()) {
    P p = q.front();
    q.pop();
    if (p.i < 0 || p.j < 0)
      continue;
    if (p.i >= h || p.j >= w)
      continue;

    if (flags[p.i][p.j])
      continue;
    flags[p.i][p.j] = true;

    if (map[p.i][p.j] == '0' + b)
      return p.t;
    if (map[p.i][p.j] == 'X')
      continue;

    p.t++;
    for (int d = 0; d < 4; d++) {
      int ni = p.i + dx[d], nj = p.j + dy[d];
      //      if( flags[ni][nj] ) continue;
      q.push(P(p.t, ni, nj));
    }
  }

  return -1;
}

int main() {
  cin >> h >> w >> n;
  for (int i = 0; i < h; i++)
    for (int j = 0; j < w; j++)
      cin >> map[i][j];

  int time = 0, r;
  for (int i = 0; i < n; i++) {
    r = cal(i, i + 1);
    time += r;
    //    cout << i << " => " << (i+1) << "\\t | " << r << endl;
  }
  cout << time << endl;

  return 0;
}


#include <cstdio>
#include <iostream>
#include <queue>
using namespace std;

char mem[1005][1005];

int main() {
  int h, w, n, sx, sy;
  typedef pair<int, int> P;
  queue<P> que, que2;
  int dx[4] = {-1, 0, 1, 0};
  int dy[4] = {0, 1, 0, -1};
  while (scanf("%d%d%d", &h, &w, &n) != EOF && h && w) {
    for (int i = 0; i < h; i++)
      for (int j = 0; j < w; j++) {
        scanf("%c", &mem[i][j]);
        if (mem[i][j] == ' ' || mem[i][j] == '\\n')
          j--;
        if (mem[i][j] == 'S') {
          sx = i;
          sy = j;
        }
      }
    while (que.size()) {
      que.pop();
      que2.pop();
    }
    que.push(P(sx, sy));
    que2.push(P(0, 1));
    bool is_find = false;
    while (!is_find) {
      P xy = que.front();
      que.pop();
      int x = xy.first;
      int y = xy.second;
      P date = que2.front();
      que2.pop();
      for (int i = 0; i < 4; i++) {
        if ((x + dx[i] >= 0 && y + dy[i] >= 0) &&
            (x + dx[i] < h && y + dy[i] < w)) {
          if (mem[x + dx[i]][y + dy[i]] == 'X')
            continue;
          else {
            if (date.second == (mem[x + dx[i]][y + dy[i]] - '0')) {
              if (date.second == n) {
                is_find = true;
                printf("%d\\n", date.first + 1);
              } else {
                que.push(P(x + dx[i], y + dy[i]));
                que2.push(P(date.first + 1, date.second + 1));
              }
              break;
            } else {
              que.push(P(x + dx[i], y + dy[i]));
              que2.push(P(date.first + 1, date.second));
            }
          }
        }
      }
    }
  }
  return 0;
}

#include <cstdio>
#include <iostream>
// #include <cmath>
#include <algorithm>
#include <cstring>
#include <functional>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <vector>

#define CL(arr, val) memset(arr, val, sizeof(arr))

#define ll long long
#define inf 0x7f7f7f7f
#define lc l, m, rt << 1
#define rc m + 1, r, rt << 1 | 1
#define pi acos(-1.0)

#define L(x) (x) << 1
#define R(x) (x) << 1 | 1
#define MID(l, r) (l + r) >> 1
#define Min(x, y) (x) < (y) ? (x) : (y)
#define Max(x, y) (x) < (y) ? (y) : (x)
#define E(x) (1 << (x))
#define iabs(x) (x) < 0 ? -(x) : (x)
#define OUT(x) printf("%I64d\\n", x)
#define lowbit(x) (x) & (-x)
#define Read() freopen("a.txt", "r", stdin)
#define Write() freopen("dout.txt", "w", stdout);
#define maxn 1000000000
#define N 1010
using namespace std;

int h, w, x;
int dir[4][2] = {-1, 0, 0, 1, 0, -1, 1, 0};
typedef pair<int, int> P;
P p;
char maze[N][N];
int d[N][N];

int bfs(char c) {
  queue<P> que;
  for (int i = 0; i < h; i++)
    for (int j = 0; j < w; j++)
      d[i][j] = maxn;
  que.push(p);
  d[p.first][p.second] = 0;
  P p1, p2;
  while (que.size()) {
    p1 = que.front();
    que.pop();
    if (maze[p1.first][p1.second] == c) {
      p = p1;
      break;
    }
    for (int i = 0; i < 4; i++) {
      p2.first = p1.first + dir[i][0];
      p2.second = p1.second + dir[i][1];
      if (p2.first >= 0 && p2.first < h && p2.second >= 0 && p2.second < w &&
          maze[p2.first][p2.second] != 'X' && d[p2.first][p2.second] == maxn) {
        que.push(p2);
        d[p2.first][p2.second] = d[p1.first][p1.second] + 1;
      }
    }
  }
  return d[p.first][p.second];
}

int main() {
  // freopen("a.txt","r",stdin);
  while (~scanf("%d%d%d", &h, &w, &x)) {
    getchar();
    int sum = 0;
    for (int i = 0; i < h; i++) {
      scanf("%s", maze[i]);
      // printf("%s\\n",maze[i]);
      for (int j = 0; j < w; j++) {
        if (maze[i][j] == 'S') {
          p.first = i;
          p.second = j;
        }
      }
    }
    // printf("%d %d\\n",p1.first,p1.second);
    for (int i = 1; i <= x; i++) {
      sum += bfs('0' + i);
    }
    printf("%d\\n", sum);
  }
  return 0;
}


#include <algorithm>
#include <cmath>
#include <cstdio>
#include <iostream>
#include <map>
#include <math.h>
#include <queue>
#include <set>
#include <stack>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <utility>
#include <vector>

using namespace std;

#define ll long long
#define ld long double
#define EPS 0.0000000001
#define INF 10000000000LL
#define rep(i, n) for (i = 0; i < n; i++)

typedef pair<int, int> pii;

char a[105][105];
int used[105][105] = {};
int h, w;
pii place[1000];

int search(int sx, int sy, int gx, int gy) {
  int i, j;
  int dx[4] = {-1, 0, 1, 0};
  int dy[4] = {0, -1, 0, 1};
  rep(i, h) rep(j, w) used[i][j] = 0;
  int ans = 0;
  used[sx][sy]++;
  queue<pii> q1, q2;
  q1.push(pii(sx, sy));
  while (1) {
    bool f = false;
    while (q1.size()) {
      int x = q1.front().first;
      int y = q1.front().second;
      if (x == gx && y == gy) {
        f = true;
        break;
      }
      rep(i, 4) {
        int nx = x + dx[i]; // next
        int ny = y + dy[i]; // next
        if (nx < 0 || nx >= h || ny < 0 || ny >= w)
          continue;
        if (a[nx][ny] != 'X' && used[nx][ny] == 0) {
          used[nx][ny]++;
          q2.push(pii(nx, ny));
        }
      }
      q1.pop();
    }

    if (f)
      break;

    while (q2.size()) {
      q1.push(pii(q2.front().first, q2.front().second));
      q2.pop();
    }
    ans++;
  }
  return ans;
}

int main(void) {
  int n, i, j;
  cin >> h >> w >> n;
  rep(i, h) {
    cin >> a[i];
    rep(j, w) if (a[i][j] == 'S') {
      place[0].first = i;
      place[0].second = j;
    }
    else if (a[i][j] > '0' && a[i][j] <= 'n') {
      place[a[i][j] - '0'].first = i;
      place[a[i][j] - '0'].second = j;
    }
  }

  int ans = 0;
  rep(i, n) ans += search(place[i].first, place[i].second, place[i + 1].first,
                          place[i + 1].second);

  cout << ans << endl;
  return 0;
}

#include <algorithm>
#include <cmath>
#include <cstdio>
#include <iostream>
#include <map>
#include <math.h>
#include <queue>
#include <set>
#include <stack>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <utility>
#include <vector>

using namespace std;

#define ll long long
#define ld long double
#define EPS 0.0000000001
#define INF 10000000000LL
#define rep(i, n) for (i = 0; i < n; i++)

typedef pair<int, int> pii;

char a[1005][1005];
int used[1005][1005] = {};
int h, w;
pii place[10];

int search(int sx, int sy, int gx, int gy) {
  int i, j;
  int dx[4] = {-1, 0, 1, 0};
  int dy[4] = {0, -1, 0, 1};
  rep(i, h) rep(j, w) used[i][j] = 0;
  int ans = 0;
  used[sx][sy]++;
  queue<pii> q1, q2;
  q1.push(pii(sx, sy));
  while (1) {
    bool f = false;
    while (q1.size()) {
      int x = q1.front().first;
      int y = q1.front().second;
      if (x == gx && y == gy) {
        f = true;
        break;
      }
      rep(i, 4) {
        int nx = x + dx[i]; // next
        int ny = y + dy[i]; // next
        if (nx < 0 || nx >= h || ny < 0 || ny >= w)
          continue;
        if (a[nx][ny] != 'X' && used[nx][ny] == 0) {
          used[nx][ny]++;
          q2.push(pii(nx, ny));
        }
      }
      q1.pop();
    }

    if (f)
      break;

    while (q2.size()) {
      q1.push(pii(q2.front().first, q2.front().second));
      q2.pop();
    }
    ans++;
  }
  return ans;
}

int main(void) {
  int n, i, j;
  cin >> h >> w >> n;
  rep(i, h) {
    cin >> a[i];
    rep(j, w) if (a[i][j] == 'S') {
      place[0].first = i;
      place[0].second = j;
    }
    else if (a[i][j] > '0' && a[i][j] <= 'n') {
      place[a[i][j] - '0'].first = i;
      place[a[i][j] - '0'].second = j;
    }
  }

  int ans = 0;
  rep(i, n) ans += search(place[i].first, place[i].second, place[i + 1].first,
                          place[i + 1].second);

  cout << ans << endl;
  return 0;
}


#include <iostream>
#include <math.h>
#include <stack>
#include <string>
#include <vector>
using namespace std;

int h, w, n;
int map[1000][1000];
int map_t[1000][1000];
int xxx, yyy;
int ans;

void SusundeHappy(int x, int y, int goal, int n) {
  if (map_t[x][y] == goal) {
    xxx = x;
    yyy = y;
  }
  map_t[x][y] = -1 * n;

  if (x > 0) {
    if (map_t[x - 1][y] > -1 || map_t[x - 1][y] < -1 * n) {
      SusundeHappy(x - 1, y, goal, n + 1);
    }
  }

  if (x < h - 1) {
    if (map_t[x + 1][y] > -1 || map_t[x + 1][y] < -1 * n) {
      SusundeHappy(x + 1, y, goal, n + 1);
    }
  }

  if (y > 0) {
    if (map_t[x][y - 1] > -1 || map_t[x][y - 1] < -1 * n) {
      SusundeHappy(x, y - 1, goal, n + 1);
    }
  }

  if (y < w - 1) {
    if (map_t[x][y + 1] > -1 || map_t[x][y + 1] < -1 * n) {
      SusundeHappy(x, y + 1, goal, n + 1);
    }
  }
}

int TimeFrom(int start) {
  ans = 0;
  int goal = start + 1;
  if (start == 10) {
    goal = 1;
  }

  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      if (map_t[i][j] == start) {
        SusundeHappy(i, j, goal, 1);
        return -1 * map_t[xxx][yyy] - 1;
      }
    }
  }
}

int main() {
  string line;
  while (cin >> h >> w >> n) {
    for (int i = 0; i < h; i++) {
      cin >> line;
      for (int j = 0; j < w; j++) {
        switch (line[j]) {
        case 'S':
          map[i][j] = 10;
          break;

        case '.':
          map[i][j] = 0;
          break;

        case 'X':
          map[i][j] = -1;
          break;

        default:
          map[i][j] = line[j] - '0';
          break;
        }
      }
    }

    int cnt = 0;
    for (int k = 0; k < n; k++) {
      for (int i = 0; i < h; i++) {
        for (int j = 0; j < w; j++) {
          map_t[i][j] = map[i][j];
        }
      }
      if (k == 0) {
        cnt = cnt + TimeFrom(10);
      } else {
        cnt = cnt + TimeFrom(k);
      }
    }

    cout << cnt << endl;
  }

  return 0;
}

#include <iostream>
#include <math.h>
#include <stack>
#include <string>
#include <vector>
using namespace std;

int h, w, n;
int map[1000][1000];
int map_t[1000][1000];
int step;
vector<pair<int, int>> point;

bool SearchAndCollect(int goal) {
  vector<pair<int, int>> point_t;
  for (int i = 0; i < point.size(); i++) {
    if (point[i].first > 0) {
      if (map_t[point[i].first - 1][point[i].second] == goal) {
        return true;
      } else if (map_t[point[i].first - 1][point[i].second] != -1) {
        map_t[point[i].first - 1][point[i].second] = -1;
        pair<int, int> temp;
        temp.first = point[i].first - 1;
        temp.second = point[i].second;
        point_t.push_back(temp);
      }
    }

    if (point[i].first < h - 1) {
      if (map_t[point[i].first + 1][point[i].second] == goal) {
        return true;
      } else if (map_t[point[i].first + 1][point[i].second] != -1) {
        map_t[point[i].first + 1][point[i].second] = -1;
        pair<int, int> temp;
        temp.first = point[i].first + 1;
        temp.second = point[i].second;
        point_t.push_back(temp);
      }
    }

    if (point[i].second > 0) {
      if (map_t[point[i].first][point[i].second - 1] == goal) {
        return true;
      } else if (map_t[point[i].first][point[i].second - 1] != -1) {
        map_t[point[i].first][point[i].second - 1] = -1;
        pair<int, int> temp;
        temp.first = point[i].first;
        temp.second = point[i].second - 1;
        point_t.push_back(temp);
      }
    }

    if (point[i].second < w - 1) {
      if (map_t[point[i].first][point[i].second + 1] == goal) {
        return true;
      } else if (map_t[point[i].first][point[i].second + 1] != -1) {
        map_t[point[i].first][point[i].second + 1] = -1;
        pair<int, int> temp;
        temp.first = point[i].first;
        temp.second = point[i].second + 1;
        point_t.push_back(temp);
      }
    }
  }
  point.clear();
  for (int i = 0; i < point_t.size(); i++) {
    if (point.size() <= i) {
      point.resize(point.size() + 1);
    }
    point[i] = point_t[i];
  }
  step++;
  return false;
}

int TimeFrom(int start) {
  step = 1;
  int goal = start + 1;
  if (start == 10) {
    goal = 1;
  }

  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      map_t[i][j] = map[i][j];
    }
  }

  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      if (map[i][j] == start) {
        pair<int, int> temp;
        temp.first = i;
        temp.second = j;
        point.clear();
        point.push_back(temp);
        while (SearchAndCollect(goal) == false) {
        }
        return step;
      }
    }
  }
}

int main() {
  string line;
  while (cin >> h >> w >> n) {
    for (int i = 0; i < h; i++) {
      cin >> line;
      for (int j = 0; j < w; j++) {
        switch (line[j]) {
        case 'S':
          map[i][j] = 10;
          break;

        case '.':
          map[i][j] = 0;
          break;

        case 'X':
          map[i][j] = -1;
          break;

        default:
          map[i][j] = line[j] - '0';
          break;
        }
      }
    }

    int cnt = 0;
    for (int i = 0; i < n; i++) {
      if (i == 0) {
        cnt = cnt + TimeFrom(10);
      } else {
        cnt = cnt + TimeFrom(i);
      }
    }

    cout << cnt << endl;
  }

  return 0;
}


#include <algorithm>
#include <iostream>
#include <map>
#include <queue>
#include <vector>

using namespace std;

#define rep(i, n) for (int i = 0; i < (n); ++i)

typedef pair<int, int> XY;
typedef pair<int, XY> P;

int H, W, N;
char m[1001][1001];
char checked[1001][1001];
void dfs(int i, int j) {
  char c = m[i][j];
  m[i][j] = '.';
  if (j + 1 < W && m[i][j + 1] == c)
    dfs(i, j + 1);
  if (j > 0 && m[i][j - 1] == c)
    dfs(i, j - 1);
  if (i + 1 < H && m[i + 1][j] == c)
    dfs(i + 1, j);
  if (i > 0 && m[i - 1][j] == c)
    dfs(i - 1, j);
}
int main() {
  cin >> H >> W >> N;
  int x, y;
  rep(i, H) {
    rep(j, W) {
      cin >> m[i][j];
      if (m[i][j] == 'S') {
        x = j;
        y = i;
      }
    }
  }

  int HP = 1;
  int time = 0;
  while (HP <= N) {
    rep(i, H) {
      rep(j, W) { checked[i][j] = 0; }
    }
    queue<P> q;
    q.push(P(time, XY(x, y)));
    while (q.size() > 0) {
      P p = q.front();
      q.pop();
      int cx = p.second.first;
      int cy = p.second.second;
      checked[cy][cx] = 1;
      if (m[cy][cx] == '0' + HP) {
        x = cx;
        y = cy;
        time = p.first;
        HP++;
        break;
      } else {
        if (cy > 0 && m[cy - 1][cx] != 'X' && checked[cy - 1][cx] == 0)
          q.push(P(p.first + 1, XY(cx, cy - 1)));
        if (cx > 0 && m[cy][cx - 1] != 'X' && checked[cy][cx - 1] == 0)
          q.push(P(p.first + 1, XY(cx - 1, cy)));
        if (cy < H - 1 && m[cy + 1][cx] != 'X' && checked[cy + 1][cx] == 0)
          q.push(P(p.first + 1, XY(cx, cy + 1)));
        if (cx < W - 1 && m[cy][cx + 1] != 'X' && checked[cy][cx + 1] == 0)
          q.push(P(p.first + 1, XY(cx + 1, cy)));
      }
    }
  }
  cout << time << endl;
  return 0;
}

#include <algorithm>
#include <iostream>
#include <map>
#include <queue>
#include <vector>

using namespace std;

#define rep(i, n) for (int i = 0; i < (n); ++i)

typedef pair<int, int> P;

int H, W, N;
char m[1001][1001];
int d[1001][1001];
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};

void dfs(int i, int j) {
  char c = m[i][j];
  m[i][j] = '.';
  if (j + 1 < W && m[i][j + 1] == c)
    dfs(i, j + 1);
  if (j > 0 && m[i][j - 1] == c)
    dfs(i, j - 1);
  if (i + 1 < H && m[i + 1][j] == c)
    dfs(i + 1, j);
  if (i > 0 && m[i - 1][j] == c)
    dfs(i - 1, j);
}
int main() {
  cin >> H >> W >> N;
  int x, y;
  rep(i, H) {
    rep(j, W) {
      cin >> m[i][j];
      if (m[i][j] == 'S') {
        x = j;
        y = i;
      }
    }
  }

  int HP = 1;
  int time = 0;
  int dist = 0;
  while (HP <= N) {
    rep(i, H) {
      rep(j, W) { d[i][j] = -1; }
    }
    d[y][x] = dist;
    queue<P> q;
    q.push(P(x, y));
    while (q.size() > 0) {
      P p = q.front();
      q.pop();
      int cx = p.first;
      int cy = p.second;
      if (m[cy][cx] == '0' + HP) {
        x = cx;
        y = cy;
        dist = d[y][x];
        HP++;
        break;
      }
      rep(i, 4) {
        int nx = cx + dx[i];
        int ny = cy + dy[i];
        if (0 <= nx && nx < W && 0 <= ny && ny < H && d[ny][nx] == -1 &&
            m[ny][nx] != 'X') {
          q.push(P(nx, ny));
          d[ny][nx] = d[cy][cx] + 1;
        }
      }
    }
  }
  cout << dist << endl;
  return 0;
}


#include <iostream>
#include <vector>
std::vector<std::pair<int, int>> next_list(const int &x, const int &y) {
  return {std::make_pair(x + 1, y), std::make_pair(x - 1, y),
          std::make_pair(x, y + 1), std::make_pair(x, y - 1)};
}
template <typename T> class Queue {
public:
  Queue(const int &n) : vector(n), f(0), b(0){};
  T front() const { return vector.at(f); }
  T back() const { return vector.at(b); }
  void pop() { f = (f + 1) % vector.size(); }
  void push(T f) {
    vector.at(b) = f;
    b = (b + 1) % vector.size();
  }
  void clear() {
    f = 0;
    b = 0;
  }

private:
  std::vector<T> vector;
  int f, b;
};
struct Route {
  Route(const int &ax = 0, const int &ay = 0, const int &an = 0,
        const int &atime = 0)
      : x(ax), y(ay), n(an), time(atime){};
  int x, y, n, time;
  bool operator<(const Route &other) const { return time < other.time; }
};
int wfs(const std::vector<std::vector<int>> &vector,
        std::vector<std::vector<int>> &memo, Queue<Route> &queue,
        const Route &start, const int &goal) {
  queue.clear();
  queue.push(start);
  while (vector.at(queue.front().y).at(queue.front().x) != start.n + 1) {
    for (const auto &coord : next_list(queue.front().x, queue.front().y)) {
      if (vector.at(coord.second).at(coord.first) >= 0 &&
          memo.at(coord.second).at(coord.first) != start.n) {
        memo.at(coord.second).at(coord.first) = start.n;
        queue.push(Route(coord.first, coord.second, 0, queue.front().time + 1));
      }
    }
    queue.pop();
  }
  if (start.n + 1 == goal) {
    return queue.front().time;
  } else {
    return wfs(vector, memo, queue,
               Route(queue.front().x, queue.front().y, start.n + 1,
                     queue.front().time),
               goal);
  }
}
int main() {
  int h, w, n;
  std::cin >> h >> w >> n;
  std::vector<std::vector<int>> vector(h + 2, std::vector<int>(w + 2, -1));
  Route start(0, 0, 0, 0);
  char *arg = new char[w + 2];
  for (auto i = 1; i <= h; ++i) {
    std::cin >> arg;
    for (auto j = 1; j <= w; ++j) {
      switch (arg[j - 1]) {
      case '.':
        vector.at(i).at(j) = 0;
        break;
      case 'X':
        vector.at(i).at(j) = -1;
        break;
      case 'S':
        vector.at(i).at(j) = 0;
        start = Route(j, i, 0, 0);
        break;
      default:
        vector.at(i).at(j) = arg[j - 1] - '0';
      }
    }
  }
  delete[] arg;
  arg = nullptr;
  std::vector<std::vector<int>> memo(h + 2, std::vector<int>(w + 2, -1));
  Queue<Route> queue(h * w * 4);
  std::cout << wfs(vector, memo, queue, start, n) << std::endl;
  return 0;
}

#include <iostream>
#include <vector>
std::vector<std::pair<int, int>> next_list(const int &x, const int &y) {
  return {std::make_pair(x + 1, y), std::make_pair(x - 1, y),
          std::make_pair(x, y + 1), std::make_pair(x, y - 1)};
}
template <typename T> class Queue {
public:
  Queue(const int &n) : vector(n), f(0), b(0){};
  T front() const { return vector.at(f); }
  T back() const { return vector.at(b); }
  void pop() { f = (f + 1) % vector.size(); }
  void push(T f) {
    vector.at(b) = f;
    b = (b + 1) % vector.size();
  }
  void clear() {
    f = 0;
    b = 0;
  }

private:
  std::vector<T> vector;
  int f, b;
};
struct Route {
  Route(const int &ax = 0, const int &ay = 0, const int &an = 0,
        const int &atime = 0)
      : x(ax), y(ay), n(an), time(atime){};
  int x, y, n, time;
  bool operator<(const Route &other) const { return time < other.time; }
};
int wfs(const std::vector<std::vector<int>> &vector,
        std::vector<std::vector<int>> &memo, Queue<Route> &queue,
        const Route &start, const int &goal) {
  queue.clear();
  queue.push(start);
  while (vector.at(queue.front().y).at(queue.front().x) != start.n + 1) {
    for (const auto &coord : next_list(queue.front().x, queue.front().y)) {
      if (vector.at(coord.second).at(coord.first) >= 0 &&
          memo.at(coord.second).at(coord.first) != start.n) {
        memo.at(coord.second).at(coord.first) = start.n;
        queue.push(Route(coord.first, coord.second, 0, queue.front().time + 1));
      }
    }
    queue.pop();
  }
  if (start.n + 1 == goal) {
    return queue.front().time;
  } else {
    return wfs(vector, memo, queue,
               Route(queue.front().x, queue.front().y, start.n + 1,
                     queue.front().time),
               goal);
  }
}
int main() {
  int h, w, n;
  std::cin >> h >> w >> n;
  std::vector<std::vector<int>> vector(h + 2, std::vector<int>(w + 2, -1));
  Route start(0, 0, 0, 0);
  char *arg = new char[w + 2];
  for (auto i = 1; i <= h; ++i) {
    std::cin >> arg;
    for (auto j = 1; j <= w; ++j) {
      switch (arg[j - 1]) {
      case '.':
        vector.at(i).at(j) = 0;
        break;
      case 'X':
        vector.at(i).at(j) = -1;
        break;
      case 'S':
        vector.at(i).at(j) = 0;
        start = Route(j, i, 0, 0);
        break;
      default:
        vector.at(i).at(j) = arg[j - 1] - '0';
      }
    }
  }
  delete[] arg;
  arg = nullptr;
  std::vector<std::vector<int>> memo(h + 2, std::vector<int>(w + 2, -1));
  Queue<Route> queue(h * w);
  std::cout << wfs(vector, memo, queue, start, n) << std::endl;
  return 0;
}


#include <iostream>
#include <queue>
#include <utility>
#include <vector>
using namespace std;

typedef pair<int, int> P;

int main() {
  int H, W, N, gn = 0, res = 0;
  cin >> H >> W >> N;
  char ch;
  vector<vector<int>> a(W, vector<int>(H, 1000002));
  P start;
  vector<P> goal(N);

  for (int i = 0; i < H; i++) {
    for (int j = 0; j < W; j++) {
      cin >> ch;
      if (ch == 'X') {
        a[j][i] = -1;
      } else if (ch == 'S') {
        start.first = j;
        start.second = i;
      } else if (ch >= '1' && ch <= '9') {
        goal[ch - '1'].first = j;
        goal[ch - '1'].second = i;
      }
    }
  }
  while (gn < N) {
    int ite = 1;
    queue<P> bfs;
    bfs.push(start);
    a[start.first][start.second] = 0;
    while (!bfs.empty()) {
      P temp = bfs.front();
      bfs.pop();
      if (temp.first + 1 < W && a[temp.first + 1][temp.second] == 1000002) {
        if (goal[gn].first == temp.first + 1 &&
            goal[gn].second == temp.second) {
          res += ite;
          break;
        } else {
          a[temp.first + 1][temp.second] = ite;
          bfs.push(P(temp.first + 1, temp.second));
        }
      }
      if (temp.first - 1 >= 0 && a[temp.first - 1][temp.second] == 1000002) {
        if (goal[gn].first == temp.first - 1 &&
            goal[gn].second == temp.second) {
          res += ite;
          break;
        } else {
          a[temp.first - 1][temp.second] = ite;
          bfs.push(P(temp.first - 1, temp.second));
        }
      }
      a[temp.first - 1][temp.second] = ite;
      if (temp.second + 1 < H && a[temp.first][temp.second + 1] == 1000002) {
        if (goal[gn].first == temp.first &&
            goal[gn].second == temp.second + 1) {
          res += ite;
          break;
        } else {
          a[temp.first][temp.second + 1] = ite;
          bfs.push(P(temp.first, temp.second + 1));
        }
      }
      if (temp.second - 1 >= 0 && a[temp.first][temp.second - 1] == 1000002) {
        if (goal[gn].first == temp.first &&
            goal[gn].second == temp.second - 1) {
          res += ite;
          break;
        } else {
          a[temp.first][temp.second - 1] = ite;
          bfs.push(P(temp.first, temp.second - 1));
        }
      }

      ite++;
    }
    for (int i = 0; i < H; i++) {
      for (int j = 0; j < W; j++) {
        if (a[j][i] != -1) {
          a[j][i] = 1000002;
        }
      }
    }
    start = goal[gn];
    gn++;
  }
  cout << res << endl;
  return 0;
}

#include <iostream>
#include <queue>
#include <utility>
#include <vector>
using namespace std;

typedef pair<int, int> P;

int main() {
  int H, W, N, gn = 0, res = 0;
  cin >> H >> W >> N;
  char ch;
  vector<vector<int>> a(W, vector<int>(H, 1000002));
  P start;
  vector<P> goal(N);

  for (int i = 0; i < H; i++) {
    for (int j = 0; j < W; j++) {
      cin >> ch;
      if (ch == 'X') {
        a[j][i] = -1;
      } else if (ch == 'S') {
        start.first = j;
        start.second = i;
      } else if (ch >= '1' && ch <= '9') {
        goal[ch - '1'].first = j;
        goal[ch - '1'].second = i;
      }
    }
  }
  while (gn < N) {
    queue<P> bfs;
    bfs.push(start);
    a[start.first][start.second] = 0;
    while (!bfs.empty()) {
      P temp = bfs.front();
      bfs.pop();
      if (temp.first + 1 < W && a[temp.first + 1][temp.second] == 1000002) {
        if (goal[gn].first == temp.first + 1 &&
            goal[gn].second == temp.second) {
          res += a[temp.first][temp.second] + 1;
          break;
        } else {
          a[temp.first + 1][temp.second] = a[temp.first][temp.second] + 1;
          bfs.push(P(temp.first + 1, temp.second));
        }
      }
      if (temp.first - 1 >= 0 && a[temp.first - 1][temp.second] == 1000002) {
        if (goal[gn].first == temp.first - 1 &&
            goal[gn].second == temp.second) {
          res += a[temp.first][temp.second] + 1;
          break;
        } else {
          a[temp.first - 1][temp.second] = a[temp.first][temp.second] + 1;
          bfs.push(P(temp.first - 1, temp.second));
        }
      }
      if (temp.second + 1 < H && a[temp.first][temp.second + 1] == 1000002) {
        if (goal[gn].first == temp.first &&
            goal[gn].second == temp.second + 1) {
          res += a[temp.first][temp.second] + 1;
          break;
        } else {
          a[temp.first][temp.second + 1] = a[temp.first][temp.second] + 1;
          bfs.push(P(temp.first, temp.second + 1));
        }
      }
      if (temp.second - 1 >= 0 && a[temp.first][temp.second - 1] == 1000002) {
        if (goal[gn].first == temp.first &&
            goal[gn].second == temp.second - 1) {
          res += a[temp.first][temp.second] + 1;
          break;
        } else {
          a[temp.first][temp.second - 1] = a[temp.first][temp.second] + 1;
          bfs.push(P(temp.first, temp.second - 1));
        }
      }
    }
    for (int i = 0; i < H; i++) {
      for (int j = 0; j < W; j++) {
        if (a[j][i] != -1) {
          a[j][i] = 1000002;
        }
      }
    }
    start = goal[gn];
    gn++;
  }
  cout << res << endl;
  return 0;
}


#include <algorithm>
#include <iostream>
#include <queue>

using namespace std;

struct P {
  int s;
  int t;
};

struct P2 {
  int s;
  int t;
  int c;
};

int ds[4] = {0, 1, 0, -1}, dt[4] = {1, 0, -1, 0};

int bfs(char ch[1001][1001], P st, P go, int w, int h) {
  bool fa[1001][1001];
  fill(&fa[0][0], &fa[1000][1000], true);
  P2 p, q;
  queue<P2> que;
  p.s = st.s;
  p.t = st.t;
  p.c = 0;
  que.push(p);
  int c = 0;
  while (!que.empty()) {
    p = que.front();
    que.pop();

    if (p.s == go.s && p.t == go.t) {
      c = p.c;
      break;
    }

    for (int i = 0; i < 4; i++) {
      q.s = p.s + ds[i];
      q.t = p.t + dt[i];
      if (q.s >= 0 && q.s < h && q.t >= 0 && q.t < w) {
        if (fa[q.s][q.t] && ch[q.s][q.t] != 'X') {
          fa[q.s][q.t] = false;
          q.c = p.c + 1;
          que.push(q);
        }
      }
    }
  }

  return c;
}

int main() {
  int w, h, n, c;
  char ch[1001][1001];
  P pa[10];

  while (cin >> h >> w >> n && h && w && n) {
    for (int i = 0; i < h; i++) {
      for (int j = 0; j < w; j++) {
        cin >> ch[i][j];
        if (ch[i][j] == 'S') {
          pa[0].s = i;
          pa[0].t = j;
        } else if (ch[i][j] != '.' || ch[i][j] != 'X') {
          pa[(int)(ch[i][j] - '0')].s = i;
          pa[(int)(ch[i][j] - '0')].t = j;
        }
      }
    }
    c = 0;

    for (int i = 0; i < n; i++) {
      c += bfs(ch, pa[i], pa[i + 1], w, h);
    }

    cout << c << endl;
  }

  return 0;
}


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

int h, w, n;
char m[1010][1010];
int d[1010][1010];
int dx[] = {0, 0, 1, -1}, dy[] = {1, -1, 0, 0};

void init() {
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      d[i][j] = 1e9 + 9;
    }
  }
}

int main() {
  int sx, sy;

  cin >> h >> w >> n;
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      cin >> m[i][j];
      if (m[i][j] == 'S')
        sx = j, sy = i;
    }
  }

  int ans = 0;
  for (int i = 1; i <= n; i++) {
    queue<pair<int, int>> q;
    q.push(make_pair(sy, sx));

    init();
    d[sy][sx] = 0;
    while (!q.empty()) {
      pair<int, int> nv = q.front();
      q.pop();

      if (m[nv.first][nv.second] == '0' + i) {
        sy = nv.first;
        sx = nv.second;
        ans += d[sy][sx];
        while (!q.empty())
          q.pop();
        break;
      }

      for (int j = 0; j < 4; j++) {
        int ny = nv.first + dy[j];
        int nx = nv.second + dx[j];
        if (ny < 0 || h <= ny || nx < 0 || w <= nx)
          continue;
        if (d[ny][nx] < d[nv.first][nv.second])
          continue;
        if (m[ny][nx] == 'X')
          continue;
        d[ny][nx] = d[nv.first][nv.second] + 1;
        q.push(make_pair(ny, nx));
      }
    }
  }

  cout << ans << endl;
}

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

int h, w, n;
char m[1010][1010];
int d[1010][1010];
bool f[1010][1010];

int dx[] = {0, 0, 1, -1}, dy[] = {1, -1, 0, 0};

void init() {
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      d[i][j] = 1e9 + 9;
      f[i][j] = false;
    }
  }
}

int main() {
  int sx, sy;

  cin >> h >> w >> n;
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      cin >> m[i][j];
      if (m[i][j] == 'S')
        sx = j, sy = i;
    }
  }

  int ans = 0;
  for (int i = 1; i <= n; i++) {
    queue<pair<int, int>> q;
    q.push(make_pair(sy, sx));

    init();
    f[sy][sx] = true;
    d[sy][sx] = 0;
    while (!q.empty()) {
      pair<int, int> nv = q.front();
      q.pop();

      if (m[nv.first][nv.second] == '0' + i) {
        sy = nv.first;
        sx = nv.second;
        ans += d[sy][sx];
        while (!q.empty())
          q.pop();
        break;
      }

      for (int j = 0; j < 4; j++) {
        int ny = nv.first + dy[j];
        int nx = nv.second + dx[j];
        if (ny < 0 || h <= ny || nx < 0 || w <= nx)
          continue;
        if (f[ny][nx])
          continue;
        if (m[ny][nx] == 'X')
          continue;
        d[ny][nx] = d[nv.first][nv.second] + 1;
        q.push(make_pair(ny, nx));
        f[ny][nx] = true;
      }
    }
  }

  cout << ans << endl;
}


#include <cstdio>
#include <iostream>
#include <queue>
#include <tuple>

#define MAX_W 1010
#define MAX_H 1010

using namespace std;

int w, h, n;
char sections[MAX_H][MAX_W];
bool visited[MAX_H][MAX_W];
int dx[] = {1, 0, -1, 0};
int dy[] = {0, -1, 0, 1};

tuple<int, int, int> bfs(queue<tuple<int, int, int>> &que, int hp) {
  if (que.empty())
    return make_tuple(-1, -1, -1);
  int x, y, d;
  tie(x, y, d) = que.front();
  que.pop();
  visited[y][x] = true;
  for (int i = 0; i < 4; ++i) {
    int nx = x + dx[i], ny = y + dy[i];
    if ((0 <= nx && nx < w && 0 <= ny && ny < h) &&
        (!visited[ny][nx] && sections[ny][nx] != 'X')) {
      if (sections[ny][nx] == ('0' + hp))
        return make_tuple(nx, ny, d + 1);
      else {
        visited[ny][nx] = true;
        que.push(make_tuple(nx, ny, d + 1));
      }
    }
  }
  return bfs(que, hp);
}

int main() {
  scanf("%d %d %d", &h, &w, &n);
  for (int i = 0; i < h; ++i) {
    scanf("%s", sections[i]);
  }

  int sx, sy;
  for (int i = 0; i < h; ++i) {
    for (int j = 0; j < w; ++j) {
      if (sections[i][j] == 'S') {
        sx = j;
        sy = i;
      }
    }
  }

  int ans = 0;
  queue<tuple<int, int, int>> que;
  que.push(make_tuple(sx, sy, 0));
  for (int hp = 1; hp <= n; ++hp) {
    for (int i = 0; i < h; ++i) {
      for (int j = 0; j < w; ++j) {
        visited[i][j] = false;
      }
    }
    int x, y, d;
    tie(x, y, d) = bfs(que, hp);
    ans += d;
    que = queue<tuple<int, int, int>>();
    que.push(make_tuple(x, y, 0));
  }
  printf("%d\\n", ans);

  return 0;
}

#include <cstdio>
#include <iostream>
#include <queue>
#include <tuple>

#define MAX_W 1010
#define MAX_H 1010

using namespace std;

int w, h, n;
char sections[MAX_H][MAX_W];
bool visited[MAX_H][MAX_W];
int dx[] = {1, 0, -1, 0};
int dy[] = {0, -1, 0, 1};

int main() {
  scanf("%d %d %d", &h, &w, &n);
  for (int i = 0; i < h; ++i) {
    scanf("%s", sections[i]);
  }

  int sx, sy;
  for (int i = 0; i < h; ++i) {
    for (int j = 0; j < w; ++j) {
      if (sections[i][j] == 'S') {
        sx = j;
        sy = i;
      }
    }
  }

  int ans = 0;
  queue<tuple<int, int, int>> que;
  que.push(make_tuple(sx, sy, 0));
  for (int hp = 1; hp <= n; ++hp) {
    for (int i = 0; i < h; ++i) {
      for (int j = 0; j < w; ++j) {
        visited[i][j] = false;
      }
    }

    tuple<int, int, int> res;
    while (!que.empty()) {
      int x, y, d;
      tie(x, y, d) = que.front();
      que.pop();
      visited[y][x] = true;
      for (int i = 0; i < 4; ++i) {
        int nx = x + dx[i], ny = y + dy[i];
        if ((0 <= nx && nx < w && 0 <= ny && ny < h) &&
            (!visited[ny][nx] && sections[ny][nx] != 'X')) {
          if (sections[ny][nx] == ('0' + hp)) {
            visited[ny][nx] = true;
            res = make_tuple(nx, ny, d + 1);
          } else {
            visited[ny][nx] = true;
            que.push(make_tuple(nx, ny, d + 1));
          }
        }
      }
    }

    int x, y, d;
    tie(x, y, d) = res;
    ans += d;
    que = queue<tuple<int, int, int>>();
    que.push(make_tuple(x, y, 0));
  }
  printf("%d\\n", ans);

  return 0;
}


#include <algorithm>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <queue>

using namespace std;

typedef pair<int, int> P;

const int INF = 100000000;
const int MAX_H = 1000;
const int MAX_W = 1000;
const int MAX_N = 9;

//输入
int H, W, N;
char maze[MAX_H][MAX_W + 1];

int sx, sy;
int d[MAX_H][MAX_W];

const int dx[4] = {-1, 1, 0, 0};
const int dy[4] = {0, 0, -1, 1};

// 求以(sx, sy)为起点到达目标c的最短路径长度
int bfs(char c) {
  // 初始化
  memset(d, -1, sizeof(d));
  d[sx][sy] = 0;
  queue<P> que;
  que.push(P(sx, sy));
  //宽度优先
  while (!que.empty()) {
    P p = que.front();
    que.pop();
    // 已找到
    if (maze[p.first][p.second] == c) {
      // 重置起点
      sx = p.first;
      sy = p.second;
      break;
    }

    for (int i = 0; i < 4; i++) {
      int nx = p.first + dx[i], ny = p.second + dy[i];
      // 判断是否可移动以及是否已经访问过
      if (0 <= nx && nx < H && 0 <= ny && ny < W && maze[nx][ny] != 'X' &&
          d[nx][ny] == -1) {
        que.push(P(nx, ny));
        d[nx][ny] = d[p.first][p.second] + 1;
      }
    }
  }
  return d[sx][sy];
}

void solve() {
  // 找起始点
  for (int i = 0; i < H; i++) {
    for (int j = 0; j < W; j++) {
      if (maze[i][j] == 'S') {
        sx = i;
        sy = j;
        break;
      }
    }
  }
  //宽度优先搜索
  int ans = 0;
  for (int i = 1; i <= N; i++) {
    ans += bfs('0' + i);
  }
  printf("%d\\n", ans);
}

int main(int argc, char const *argv[]) {

  while (scanf("%d %d %d", &H, &W, &N)) {
    for (int i = 0; i < H; i++) {
      scanf("%s", maze[i]);
    }
    solve();
  }

  return 0;
}

#include <algorithm>
#include <cstdio>
#include <iostream>
#include <queue>

using namespace std;

typedef pair<int, int> P;

const int INF = 100000000;
const int MAX_H = 1000;
const int MAX_W = 1000;
const int MAX_N = 9;

//输入
int H, W, N;
char maze[MAX_H][MAX_W + 1];

int sx, sy;
int d[MAX_H][MAX_W];

const int dx[4] = {-1, 1, 0, 0};
const int dy[4] = {0, 0, -1, 1};

// 求以(sx, sy)为起点到达目标c的最短路径长度
int bfs(char c) {
  // 初始化
  for (int i = 0; i < H; i++) {
    fill(d[i], d[i] + W, INF);
  }
  d[sx][sy] = 0;
  queue<P> que;
  que.push(P(sx, sy));
  //宽度优先
  while (!que.empty()) {
    P p = que.front();
    que.pop();
    // 已找到
    if (maze[p.first][p.second] == c) {
      // 重置起点
      sx = p.first;
      sy = p.second;
      break;
    }

    for (int i = 0; i < 4; i++) {
      int nx = p.first + dx[i], ny = p.second + dy[i];
      // 判断是否可移动以及是否已经访问过
      if (0 <= nx && nx < H && 0 <= ny && ny < W && maze[nx][ny] != 'X' &&
          d[nx][ny] == INF) {
        que.push(P(nx, ny));
        d[nx][ny] = d[p.first][p.second] + 1;
      }
    }
  }
  //	printf("%d, %d\\n", sx, sy);
  return d[sx][sy];
}

void solve() {
  // 找起始点
  for (int i = 0; i < H; i++) {
    for (int j = 0; j < W; j++) {
      if (maze[i][j] == 'S') {
        sx = i;
        sy = j;
        break;
      }
    }
  }
  //宽度优先搜索
  int ans = 0;
  for (int i = 1; i <= N; i++) {
    ans += bfs('0' + i);
  }
  printf("%d\\n", ans);
}

int main(int argc, char const *argv[]) {

  scanf("%d %d %d", &H, &W, &N);
  for (int i = 0; i < H; i++) {
    scanf("%s", maze[i]);
  }
  solve();

  return 0;
}


#include <cstring>
#include <iostream>
#include <queue>
#include <stdio.h>
using namespace std;

char ma[1005][1005];
int vis[1005][1005];
int w, h, n;

int dx[] = {1, 0, -1, 0};
int dy[] = {0, 1, 0, -1};

struct node {
  int x, y, time;
};
node start;

void bfs(char ed) {
  queue<node> que;
  que.push(start);
  vis[start.x][start.y] = 1;
  while (!que.empty()) {
    node no = que.front();
    que.pop();
    for (int i = 0; i < 4; i++) {
      int x = no.x + dx[i];
      int y = no.y + dy[i];
      if (vis[x][y] || x >= h || x < 0 || y >= w || y < 0 || ma[x][y] == 'X')
        continue;
      if (ma[x][y] == ed) {
        start.x = x;
        start.y = y;
        start.time = no.time + 1;
        return;
      }
      vis[x][y] = 1;
      node no1;
      no1.x = x;
      no1.y = y;
      no1.time = no.time + 1;
      que.push(no1);
    }
  }
}

int main() {
  while (~scanf("%d %d %d", &h, &w, &n)) {
    for (int i = 0; i < h; i++) {
      scanf("%s", &ma[i]);
      for (int j = 0; j < w; j++)
        if (ma[i][j] == 'S') {
          start.x = i;
          start.y = j;
          start.time = 0;
        }
    }
    for (int i = 0; i < n; i++) {
      memset(vis, 0, sizeof(vis));
      bfs(i + '1');
    }

    printf("%d\\n", start.time);
  }
}

#include <algorithm>
#include <cstdio>
#include <iostream>
#include <queue>
#define inf 1000000
using namespace std;
int H, W, N, x0, y0;
char map[1005][1005];
int d[1005][1005];
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, -1, 0, 1};
typedef pair<int, int> P;
struct position {
  int rx, ry, e;
} xy[9];
bool comp(const position a, const position b) { return a.e < b.e; }
int bfs(int sx, int sy, int gx, int gy) {
  int tx, ty;
  queue<P> q;

  for (int i = 0; i < H; i++) {
    for (int j = 0; j < W; j++)
      d[i][j] = inf;
  }
  q.push(P(sx, sy));
  d[sx][sy] = 0;
  while (!q.empty()) {
    P p = q.front();
    if (p.first == gx && p.second == gy)
      return d[p.first][p.second];
    q.pop();
    for (int i = 0; i < 4; i++) {
      tx = p.first + dx[i];
      ty = p.second + dy[i];
      if (tx >= 0 && tx < H && ty >= 0 && ty < W && map[tx][ty] != 'X' &&
          d[tx][ty] == inf) {
        d[tx][ty] = d[p.first][p.second] + 1;
        q.push(P(tx, ty));
      }
    }
  }
}
int main(void) {
  while (scanf("%d%d%d", &H, &W, &N) == 3) {
    int x1[9], y1[9];
    for (int i = 0; i < H; i++)
      scanf("%s", &map[i]);
    int t = 0;
    for (int i = 0; i < H; i++) {
      for (int j = 0; j < W; j++) {
        if (map[i][j] == 'S') {
          x0 = i;
          y0 = j;
        }
        if (map[i][j] - '0' > 0 && map[i][j] - '0' <= 9) {
          xy[t].rx = i;
          xy[t].ry = j;
          xy[t].e = map[i][j] - '0';
          t++;
        }
      }
    }

    sort(xy, xy + N, comp);
    int ans = bfs(x0, y0, xy[0].rx, xy[0].ry);
    for (int i = 0; i < N - 1; i++)
      ans += bfs(xy[i].rx, xy[i].ry, xy[i + 1].rx, xy[i + 1].ry);
    printf("%d\\n", ans);
  }
  return 0;
}


#include <iostream>
#include <utility>
#include <vector>

using namespace std;

int H, W, N;
char mapT[1000][1000];
char temp_map[1000][1000];

int temp_x = 0, temp_y;
char temp;
int min_rou = 0;
int min_route = 500000;
int final_min_route = 0;
vector<pair<int, int>> dir;

void findSmallRoute(int x, int y, char &factory) {
  if (mapT[x][y] == factory) {
    ++min_rou;
    if (min_route > (min_rou - 1)) {
      min_route = min_rou - 1;
      temp_x = x;
      temp_y = y;
    }
    --min_rou;
    return;
  }
  if (x < 0 || y >= W || x >= H || y < 0 || mapT[x][y] == 'X') {
    return;
  }
  ++min_rou;
  mapT[x][y] = 'X';
  for (vector<pair<int, int>>::iterator it = dir.begin(); it != dir.end();
       ++it) {
    findSmallRoute(x + it->first, y + it->second, factory);
  }
  mapT[x][y] = temp_map[x][y];
  --min_rou;
  return;
}

int main() {
  dir.push_back({-1, 0});
  dir.push_back({0, 1});
  dir.push_back({1, 0});
  dir.push_back({0, -1});
  int start_X = 0, start_Y = 0;
  cin >> H >> W >> N;
  for (int i = 0; i < H; i++) {
    for (int j = 0; j < W; ++j) {
      cin >> temp;
      mapT[i][j] = temp;
      if (temp == 'S') {
        start_X = i;
        start_Y = j;
      }
    }
  }

  for (int i = 0; i < H; ++i) {
    for (int j = 0; j < W; ++j) {
      temp_map[i][j] = mapT[i][j];
    }
  }

  for (int factory = 1; factory != N + 1; ++factory) {

    char n = factory + '0';
    findSmallRoute(start_X, start_Y, n);
    for (int i = 0; i < H; ++i) {
      for (int j = 0; j < W; ++j) {
        mapT[i][j] = temp_map[i][j];
      }
    }
    final_min_route += min_route;
    min_rou = 0;
    min_route = 500000;

    start_X = temp_x;
    start_Y = temp_y;
  }

  cout << final_min_route << endl;
  // system("pause");
  return 0;
}

#include <deque>
#include <iostream>
#include <memory.h>

using namespace std;

int H, W, N;
char mapT[1000][1000];
int vis[1000][1000];
int temp_x = 0, temp_y;
char temp;
int final_min_route = 0;
int dir[4][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};

struct location {
  int x, y, route;
};

location findSmallRouteBFS(int x, int y, char factory) {
  memset(vis, 0, sizeof(vis));
  deque<location> que;
  location temp = {x, y, 0};
  que.push_back(temp);
  vis[x][y] = 1;
  while (!que.empty()) {
    location st = que.front();
    que.pop_front();
    if (mapT[st.x][st.y] == factory) {
      return st;
    }
    for (int i = 0; i < 4; ++i) {
      int t_x = st.x + dir[i][0];
      int t_y = st.y + dir[i][1];
      if (t_x < 0 || t_x >= H || t_y < 0 || t_y >= W || mapT[t_x][t_y] == 'X') {
        continue;
      }
      location temp = {t_x, t_y, st.route + 1};
      if (!vis[t_x][t_y]) {
        vis[t_x][t_y] = 1;
        que.push_back(temp);
      }
    }
  }
}

int main() {
  cin >> H >> W >> N;
  for (int i = 0; i < H; i++) {
    for (int j = 0; j < W; ++j) {
      cin >> temp;
      mapT[i][j] = temp;
      if (temp == 'S') {
        mapT[i][j] = '0';
        temp_x = i;
        temp_y = j;
      }
    }
  }

  for (int factory = 1; factory != N + 1; ++factory) {

    location lo = findSmallRouteBFS(temp_x, temp_y, mapT[temp_x][temp_y] + 1);
    temp_x = lo.x;
    temp_y = lo.y;
    final_min_route += lo.route;
  }

  cout << final_min_route << endl;
  // system("pause");
  return 0;
}


#include <cstring>
#include <iostream>
#include <queue>
#include <stdlib.h>
#define MAX_NUM 1010
using namespace std;
int H, W, N;
int flag[MAX_NUM][MAX_NUM] = {0};

class Node {
public:
  Node();
  Node(int x, int y);
  ~Node();
  int x;
  int y;
};

Node::Node() {}

Node::Node(int x, int y) {
  this->x = x;
  this->y = y;
}

Node::~Node() {}
int dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
int BFS(char map[][MAX_NUM], int sx, int sy, int ex, int ey) {
  queue<Node *> que;
  que.push(new Node(sx, sy));
  flag[sx][sy] = 0; // 将改位置???已遍?
  while (!que.empty()) {
    Node *cur = que.front();
    que.pop();
    if (cur->x == ex && cur->y == ey) {
      return flag[cur->x][cur->y];
    } else {
      for (int i = 0; i < 4; i++) // 将?位置的四个方向可以
      {
        int k = cur->x + dir[i][0];
        int v = cur->y + dir[i][1];
        if (k >= 0 && k < H && v >= 0 && v < W && map[k][v] != 'X' &&
            !flag[k][v]) {
          que.push(new Node(k, v));
          flag[k][v] = flag[cur->x][cur->y] + 1;
        }
      }
    }
  }
  return -1;
}

int main() {
  int sx, sy, arr[10][2];
  char map[MAX_NUM][MAX_NUM];
  while (cin >> H >> W >> N && H && W) {
    for (int i = 0; i < H; i++) {
      for (int j = 0; j < W; j++) {
        cin >> map[i][j];
        if (map[i][j] == 'S') {
          map[i][j] = '.';
          sx = i;
          sy = j;
        }
        if (isdigit(map[i][j])) {
          int index = map[i][j] - '0';
          arr[index][0] = i;
          arr[index][1] = j;
        }
      }
    }
    memset(flag, 0, sizeof(flag));
    int res = 0;
    res += BFS(map, sx, sy, arr[1][0], arr[1][1]);
    for (int i = 1; i + 1 <= N; i++) {
      memset(flag, 0, sizeof(flag));
      res += BFS(map, arr[i][0], arr[i][1], arr[i + 1][0], arr[i + 1][1]);
    }
    cout << res << endl;
  }
  return 0;
}

#include <iostream>
#include <queue>
using namespace std;

typedef struct {
  int x;
  int y;
} P; // 表示坐?

char graph[1000][1000];
P aim[10];
P s, g; // s起点，g?点
int N, W, H;
int vis[1000][1000]; // 用来存?距?
int dx[] = {1, 0, -1, 0}, dy[] = {0, 1, 0, -1};

int bfs(P s, P g);

int main() {
  int i, j, t, step = 0;
  cin >> H >> W >> N;

  for (i = 0; i < H; i++)
    for (j = 0; j < W; j++) {
      cin >> graph[i][j];
      if (graph[i][j] <= '9' && graph[i][j] >= '1') {
        t = graph[i][j] - '0';
        aim[t].x = i;
        aim[t].y = j;
      } // 把1-N的坐?保存在 aim数?中
      else if (graph[i][j] == 'S') {
        s.x = i;
        s.y = j;
        graph[i][j] = '.';
      } // 得到最初的起点
    }

  for (i = 1; i <= N; i++) {
    g.x = aim[i].x;
    g.y = aim[i].y; // 1-N ，从小到大，?次把一个 作??点
    step += bfs(s, g);
    s.x = g.x;
    s.y = g.y; // 到??个?点后??点?起点
    graph[g.x][g.y] = '.';
  }

  cout << step << endl;
}

int bfs(P s, P g) {
  queue<P> que;
  P n;

  for (int i = 0; i < H; i++)
    for (int j = 0; j < W; j++)
      vis[i][j] = -1;

  que.push(s);
  vis[s.x][s.y] = 0;

  while (que.size()) {

    P p = que.front();
    que.pop();
    if (p.x == g.x && p.y == g.y)
      break;

    for (int i = 0; i < 4; i++) {
      n.x = p.x + dx[i];
      n.y = p.y + dy[i]; // 向四方漫射
      if (0 <= n.x && n.x < H && 0 <= n.y && n.y < W &&
          graph[n.x][n.y] != 'X' && vis[n.x][n.y] == -1) {
        que.push(n);
        vis[n.x][n.y] = vis[p.x][p.y] + 1;
      }
    }
  }
  return vis[g.x][g.y];
}


#include <iostream>
#include <queue>
#include <stdlib.h>

using namespace std;

const int MAX_W = 1000;
const int MAX_H = 1000;
const int MAX_N = 9;

typedef pair<int, int> P;

int H, W, N;
char field[MAX_H][MAX_W];
int dist[MAX_H][MAX_W];

queue<P> que;

// using limits = std::numeric_limits<int>;

int limits = 99999;

void getStatus(int y, int x, int min_dist) {
  for (int i = 0; i < H; i++) {
    for (int j = 0; j < W; j++) {
      if (i == y && j == x) {
        cout << "$";
      } else {
        cout << field[i][j];
      }
    }
    cout << endl;
  }
  cout << "-------------min_dist:" << min_dist << endl;
}

int bfs(int goal) {

  int gx, gy;

  while (que.size()) {
    P p = que.front();
    que.pop();
    int a = p.first;
    int b = p.second;

    if (atoi(&field[p.first][p.second]) == goal) {
      gy = p.first;
      gx = p.second;
      break;
    }

    int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};

    for (int i = 0; i < 4; i++) {

      int ny = p.first + dy[i], nx = p.second + dx[i];

      if (0 <= nx && nx < W && 0 <= ny && ny < H && field[ny][nx] != 'X' &&
          dist[ny][nx] == limits) {

        que.push(P(ny, nx));
        dist[ny][nx] = dist[p.first][p.second] + 1;
      }
    }
    // getStatus(p.first,p.second,dist[p.first][p.second]);
  }

  return dist[gy][gx];
}

void init_dist() {
  for (int i = 0; i < H; i++) {
    for (int j = 0; j < W; j++) {
      dist[i][j] = limits;
    }
  }
  while (que.size()) {
    que.pop();
  }
}

void solve() {
  int sum = 0;
  for (int i = 0; i < H; i++) {
    for (int j = 0; j < W; j++) {

      if (field[i][j] == 'S') {
        init_dist();
        que.push(P(i, j));
        dist[i][j] = 0;
        sum += bfs(1);
      }

      for (int k = 1; k < N; k++) {
        if (atoi(&field[i][j]) == k) {
          init_dist();
          que.push(P(i, j));
          dist[i][j] = 0;
          sum += bfs(k + 1);
        }
      }
    }
  }

  cout << sum << endl;
}

int main() {

  while (1) {

    string line;
    cin >> H >> W >> N;
    cin.ignore();
    if (H == 0 && W == 0) {
      break;
    }

    for (int i = 0; i < H; i++) {
      getline(cin, line);
      for (int j = 0; j < W; j++) {
        field[i][j] = line[j];
      }
    }

    solve();
  }

  return 0;
}

/*
10 10 9
.X...X.S.X
6..5X..X1X
...XXXX..X
X..9X...X.
8.X2X..X3X
...XX.X4..
XX....7X..
X..X..XX..
X...X.XX..
..X.......
 */

#include <iostream>
#include <queue>
#include <stdlib.h>

using namespace std;

const int MAX_W = 1000;
const int MAX_H = 1000;
const int MAX_N = 9;

typedef pair<int, int> P;

int H, W, N;
char field[MAX_H][MAX_W];
int dist[MAX_H][MAX_W];

queue<P> que;

// using limits = std::numeric_limits<int>;

int limits = 99999;

void getStatus(int y, int x, int min_dist) {
  for (int i = 0; i < H; i++) {
    for (int j = 0; j < W; j++) {
      if (i == y && j == x) {
        cout << "$";
      } else {
        cout << field[i][j];
      }
    }
    cout << endl;
  }
  cout << "-------------min_dist:" << min_dist << endl;
}

int bfs(int goal) {

  int gx, gy;

  while (que.size()) {
    P p = que.front();
    que.pop();
    int a = p.first;
    int b = p.second;

    if (atoi(&field[p.first][p.second]) == goal) {
      gy = p.first;
      gx = p.second;
      break;
    }

    int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};

    for (int i = 0; i < 4; i++) {

      int ny = p.first + dy[i], nx = p.second + dx[i];

      if (0 <= nx && nx < W && 0 <= ny && ny < H && field[ny][nx] != 'X' &&
          dist[ny][nx] == limits) {

        que.push(P(ny, nx));
        dist[ny][nx] = dist[p.first][p.second] + 1;
      }
    }
    // getStatus(p.first,p.second,dist[p.first][p.second]);
  }

  return dist[gy][gx];
}

void init_dist() {
  for (int i = 0; i < H; i++) {
    for (int j = 0; j < W; j++) {
      dist[i][j] = limits;
    }
  }
  while (que.size()) {
    que.pop();
  }
}

void solve() {
  int sum = 0;
  for (int i = 0; i < H; i++) {
    for (int j = 0; j < W; j++) {

      if (field[i][j] == 'S') {
        init_dist();
        que.push(P(i, j));
        dist[i][j] = 0;
        sum += bfs(1);
      }

      for (int k = 1; k < N; k++) {
        if (atoi(&field[i][j]) == k) {
          init_dist();
          que.push(P(i, j));
          dist[i][j] = 0;
          sum += bfs(k + 1);
        }
      }
    }
  }

  cout << sum << endl;
}

int main() {

  // while(1){

  string line;
  cin >> H >> W >> N;
  cin.ignore();
  // if( H == 0 && W == 0 ){
  //     break;
  // }

  for (int i = 0; i < H; i++) {
    getline(cin, line);
    for (int j = 0; j < W; j++) {
      field[i][j] = line[j];
    }
  }

  solve();

  //}

  return 0;
}

/*
10 10 9
.X...X.S.X
6..5X..X1X
...XXXX..X
X..9X...X.
8.X2X..X3X
...XX.X4..
XX....7X..
X..X..XX..
X...X.XX..
..X.......
 */


#include <cstdio>
#include <iostream>
#include <vector>

const int STEP_NUM = 4;
const int STEP[STEP_NUM][STEP_NUM] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};

const int MAX_SIZE = 1000;
char field[MAX_SIZE + 1][MAX_SIZE + 1];

const int MAXN = 10;
int locationsX[MAXN];
int locationsY[MAXN];

int H, W, N;

int get_shortest_distance(int current_HP) {
  int sx = locationsX[current_HP - 1];
  int sy = locationsY[current_HP - 1];
  int ex = locationsX[current_HP];
  int ey = locationsY[current_HP];

  bool is_visit[MAX_SIZE + 1][MAX_SIZE + 1] = {};

  std::vector<std::pair<int, int>> frontier;
  frontier.push_back(std::pair<int, int>{sx, sy});
  int nx, ny;
  for (int step = 0; step < W * H; step++) {
    std::vector<std::pair<int, int>> next_frontier;
    for (auto p : frontier) {
      if (p.first == ex && p.second == ey)
        return step;
      is_visit[p.first][p.second] = true;
      for (int i = 0; i < STEP_NUM; i++) {
        nx = p.first + STEP[i][0];
        ny = p.second + STEP[i][1];
        if (nx < 0 || H <= nx)
          continue;
        if (ny < 0 || W <= ny)
          continue;
        if (field[nx][ny] == 'X')
          continue;
        if (is_visit[nx][ny])
          continue;
        next_frontier.push_back(std::make_pair(nx, ny));
      }
    }
    frontier = next_frontier;
  }
  return -1;
}

int solve() {
  int total_step = 0;
  for (int i = 1; i < N + 1; i++)
    total_step += get_shortest_distance(i);
  return total_step;
}

int main() {
  scanf("%d %d %d", &H, &W, &N);
  for (int i = 0; i < H; i++)
    scanf("%s", field[i]);
  for (int i = 0; i < H; i++)
    for (int j = 0; j < W; j++) {
      int HP = -1;
      if (field[i][j] == 'S')
        HP = 0;
      if (field[i][j] == '1')
        HP = 1;
      if (field[i][j] == '2')
        HP = 2;
      if (field[i][j] == '3')
        HP = 3;
      if (field[i][j] == '4')
        HP = 4;
      if (field[i][j] == '5')
        HP = 5;
      if (field[i][j] == '6')
        HP = 6;
      if (field[i][j] == '7')
        HP = 7;
      if (field[i][j] == '8')
        HP = 8;
      if (field[i][j] == '9')
        HP = 9;
      if (HP != -1) {
        locationsX[HP] = i;
        locationsY[HP] = j;
      }
    }
  printf("%d\\n", solve());
  return 0;
}

#include <cstdio>
#include <iostream>
#include <vector>

const int STEP_NUM = 4;
const int STEP[STEP_NUM][STEP_NUM] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};

const int MAX_SIZE = 1000;
char field[MAX_SIZE + 1][MAX_SIZE + 1];

const int MAXN = 10;
int locationsX[MAXN];
int locationsY[MAXN];

int H, W, N;

int get_shortest_distance(int current_HP) {
  int sx = locationsX[current_HP - 1];
  int sy = locationsY[current_HP - 1];
  int ex = locationsX[current_HP];
  int ey = locationsY[current_HP];

  bool is_visit[MAX_SIZE + 1][MAX_SIZE + 1] = {};
  is_visit[sx][sy] = true;

  std::vector<std::pair<int, int>> frontier;
  frontier.push_back(std::pair<int, int>{sx, sy});
  int nx, ny;
  for (int step = 0; step < W * H; step++) {
    std::vector<std::pair<int, int>> next_frontier;
    for (auto p : frontier)
      for (int i = 0; i < STEP_NUM; i++) {
        nx = p.first + STEP[i][0];
        ny = p.second + STEP[i][1];
        if (nx < 0 || H <= nx)
          continue;
        if (ny < 0 || W <= ny)
          continue;
        if (field[nx][ny] == 'X')
          continue;
        if (is_visit[nx][ny])
          continue;
        next_frontier.push_back(std::make_pair(nx, ny));
        is_visit[nx][ny] = true;
        if (nx == ex && ny == ey)
          return step + 1;
      }
    frontier = next_frontier;
  }
  return -1;
}

int solve() {
  int total_step = 0;
  for (int i = 1; i < N + 1; i++)
    total_step += get_shortest_distance(i);
  return total_step;
}

int main() {
  scanf("%d %d %d", &H, &W, &N);
  for (int i = 0; i < H; i++)
    scanf("%s", field[i]);
  for (int i = 0; i < H; i++)
    for (int j = 0; j < W; j++) {
      int HP = -1;
      if (field[i][j] == 'S')
        HP = 0;
      if (field[i][j] == '1')
        HP = 1;
      if (field[i][j] == '2')
        HP = 2;
      if (field[i][j] == '3')
        HP = 3;
      if (field[i][j] == '4')
        HP = 4;
      if (field[i][j] == '5')
        HP = 5;
      if (field[i][j] == '6')
        HP = 6;
      if (field[i][j] == '7')
        HP = 7;
      if (field[i][j] == '8')
        HP = 8;
      if (field[i][j] == '9')
        HP = 9;
      if (HP != -1) {
        locationsX[HP] = i;
        locationsY[HP] = j;
      }
    }
  printf("%d\\n", solve());
  return 0;
}


#define _CRT_SECURE_NO_WARNINGS
#include "bits/stdc++.h"
#include <random>

using namespace std;

// 呪文
#define DUMPOUT cerr
#define dump(...)                                                              \\
  DUMPOUT << "  ";                                                             \\
  DUMPOUT << #__VA_ARGS__ << " :[" << __LINE__ << ":" << __FUNCTION__ << "]"   \\
          << endl;                                                             \\
  DUMPOUT << "    ";                                                           \\
  dump_func(__VA_ARGS__)

typedef unsigned uint;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef pair<double, double> pdd;
typedef pair<string, string> pss;
template <typename _KTy, typename _Ty>
ostream &operator<<(ostream &ostr, const pair<_KTy, _Ty> &m) {
  ostr << "{" << m.first << ", " << m.second << "}";
  return ostr;
}
template <typename _KTy, typename _Ty>
ostream &operator<<(ostream &ostr, const map<_KTy, _Ty> &m) {
  if (m.empty()) {
    ostr << "{ }";
    return ostr;
  }
  ostr << "{" << *m.begin();
  for (auto itr = ++m.begin(); itr != m.end(); itr++) {
    ostr << ", " << *itr;
  }
  ostr << "}";
  return ostr;
}
template <typename _Ty>
ostream &operator<<(ostream &ostr, const vector<_Ty> &v) {
  if (v.empty()) {
    ostr << "{ }";
    return ostr;
  }
  ostr << "{" << v.front();
  for (auto itr = ++v.begin(); itr != v.end(); itr++) {
    ostr << ", " << *itr;
  }
  ostr << "}";
  return ostr;
}
template <typename _Ty> ostream &operator<<(ostream &ostr, const set<_Ty> &s) {
  if (s.empty()) {
    ostr << "{ }";
    return ostr;
  }
  ostr << "{" << *(s.begin());
  for (auto itr = ++s.begin(); itr != s.end(); itr++) {
    ostr << ", " << *itr;
  }
  ostr << "}";
  return ostr;
}
template <typename _Ty>
ostream &operator<<(ostream &ostr, const stack<_Ty> &s) {
  if (s.empty()) {
    ostr << "{ }";
    return ostr;
  }
  stack<_Ty> t(s);
  ostr << "{" << t.top();
  t.pop();
  while (!t.empty()) {
    ostr << ", " << t.top();
    t.pop();
  }
  ostr << "}";
  return ostr;
}
template <typename _Ty> ostream &operator<<(ostream &ostr, const list<_Ty> &l) {
  if (l.empty()) {
    ostr << "{ }";
    return ostr;
  }
  ostr << "{" << l.front();
  for (auto itr = ++l.begin(); itr != l.end(); ++itr) {
    ostr << ", " << *itr;
  }
  ostr << "}";
  return ostr;
}
template <typename _KTy, typename _Ty>
istream &operator>>(istream &istr, pair<_KTy, _Ty> &m) {
  istr >> m.first >> m.second;
  return istr;
}
template <typename _Ty> istream &operator>>(istream &istr, vector<_Ty> &v) {
  for (size_t i = 0; i < v.size(); i++)
    istr >> v[i];
  return istr;
}
namespace aux { // print tuple
template <typename Ty, unsigned N, unsigned L> struct tp {
  static void print(ostream &os, const Ty &v) {
    os << get<N>(v) << ", ";
    tp<Ty, N + 1, L>::print(os, v);
  }
};
template <typename Ty, unsigned N> struct tp<Ty, N, N> {
  static void print(ostream &os, const Ty &value) { os << get<N>(value); }
};
} // namespace aux
template <typename... Tys>
ostream &operator<<(ostream &os, const tuple<Tys...> &t) {
  os << "{";
  aux::tp<tuple<Tys...>, 0, sizeof...(Tys) - 1>::print(os, t);
  os << "}";
  return os;
}

template <typename A, size_t N, typename T>
inline void Fill(A (&array)[N], const T &val) {
  std::fill((T *)array, (T *)(array + N), val);
}

void dump_func() { DUMPOUT << endl; }
template <class Head, class... Tail>
void dump_func(Head &&head, Tail &&...tail) {
  DUMPOUT << head;
  if (sizeof...(Tail) == 0) {
    DUMPOUT << " ";
  } else {
    DUMPOUT << ", ";
  }
  dump_func(std::move(tail)...);
}

#define PI 3.14159265358979323846
#define EPS 1e-11
#define FOR(i, a, b) for (int i = (a); i < (b); ++i)
#define REP(i, n) FOR(i, 0, n)
#define all(x) (x).begin(), (x).end()
#define SZ(x) ((int)(x).size())
#define fake false

const int di[] = {0, -1, 0, 1};
const int dj[] = {1, 0, -1, 0};

int main() {
  // clock_t start, end;
  // start = clock();

  cin.tie(0);
  ios::sync_with_stdio(false);

  int H, W, N;
  cin >> H >> W >> N;

  vector<string> S(H);
  cin >> S;

  vector<pii> points(N + 1);

  const int space = -1;
  const int block = -2;

  vector<vector<int>> board(H, vector<int>(W, space));

  REP(i, H) REP(j, W) {
    if (S[i][j] == 'S')
      points[0] = pii(i, j);
    else if ('0' <= S[i][j] && S[i][j] <= '9')
      points[S[i][j] - '0'] = pii(i, j);
    else if (S[i][j] == 'X')
      board[i][j] = block;
  }

  int ans = 0;
  REP(k, N) {
    pii from = points[k], to = points[k + 1];

    vector<vector<int>> btmp(board);

    queue<pii> qu;
    qu.push(from);
    btmp[from.first][from.second] = 0;

    while (!qu.empty()) {
      pii p = qu.front();
      qu.pop();
      int i = p.first, j = p.second;

      int step = btmp[i][j];
      if (p == to) {
        ans += step;
        break;
      }

      REP(d, 4) {
        int ni = i + di[d], nj = j + dj[d];
        if (ni < 0 || H <= ni || nj < 0 || W <= nj)
          continue;
        if (btmp[ni][nj] == block)
          continue;
        if (btmp[ni][nj] >= 0 && btmp[ni][nj] <= step)
          continue;
        btmp[ni][nj] = step + 1;
        qu.push(pii(ni, nj));
      }
    }
  }
  cout << ans << endl;

  // end = clock();
  // printf("%d msec.\\n", end - start);

  return 0;
}

#define _CRT_SECURE_NO_WARNINGS
#include "bits/stdc++.h"
#include <random>

using namespace std;

// 呪文
#define DUMPOUT cerr
#define dump(...)                                                              \\
  DUMPOUT << "  ";                                                             \\
  DUMPOUT << #__VA_ARGS__ << " :[" << __LINE__ << ":" << __FUNCTION__ << "]"   \\
          << endl;                                                             \\
  DUMPOUT << "    ";                                                           \\
  dump_func(__VA_ARGS__)

typedef unsigned uint;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef pair<double, double> pdd;
typedef pair<string, string> pss;
template <typename _KTy, typename _Ty>
ostream &operator<<(ostream &ostr, const pair<_KTy, _Ty> &m) {
  ostr << "{" << m.first << ", " << m.second << "}";
  return ostr;
}
template <typename _KTy, typename _Ty>
ostream &operator<<(ostream &ostr, const map<_KTy, _Ty> &m) {
  if (m.empty()) {
    ostr << "{ }";
    return ostr;
  }
  ostr << "{" << *m.begin();
  for (auto itr = ++m.begin(); itr != m.end(); itr++) {
    ostr << ", " << *itr;
  }
  ostr << "}";
  return ostr;
}
template <typename _Ty>
ostream &operator<<(ostream &ostr, const vector<_Ty> &v) {
  if (v.empty()) {
    ostr << "{ }";
    return ostr;
  }
  ostr << "{" << v.front();
  for (auto itr = ++v.begin(); itr != v.end(); itr++) {
    ostr << ", " << *itr;
  }
  ostr << "}";
  return ostr;
}
template <typename _Ty> ostream &operator<<(ostream &ostr, const set<_Ty> &s) {
  if (s.empty()) {
    ostr << "{ }";
    return ostr;
  }
  ostr << "{" << *(s.begin());
  for (auto itr = ++s.begin(); itr != s.end(); itr++) {
    ostr << ", " << *itr;
  }
  ostr << "}";
  return ostr;
}
template <typename _Ty>
ostream &operator<<(ostream &ostr, const stack<_Ty> &s) {
  if (s.empty()) {
    ostr << "{ }";
    return ostr;
  }
  stack<_Ty> t(s);
  ostr << "{" << t.top();
  t.pop();
  while (!t.empty()) {
    ostr << ", " << t.top();
    t.pop();
  }
  ostr << "}";
  return ostr;
}
template <typename _Ty> ostream &operator<<(ostream &ostr, const list<_Ty> &l) {
  if (l.empty()) {
    ostr << "{ }";
    return ostr;
  }
  ostr << "{" << l.front();
  for (auto itr = ++l.begin(); itr != l.end(); ++itr) {
    ostr << ", " << *itr;
  }
  ostr << "}";
  return ostr;
}
template <typename _KTy, typename _Ty>
istream &operator>>(istream &istr, pair<_KTy, _Ty> &m) {
  istr >> m.first >> m.second;
  return istr;
}
template <typename _Ty> istream &operator>>(istream &istr, vector<_Ty> &v) {
  for (size_t i = 0; i < v.size(); i++)
    istr >> v[i];
  return istr;
}
namespace aux { // print tuple
template <typename Ty, unsigned N, unsigned L> struct tp {
  static void print(ostream &os, const Ty &v) {
    os << get<N>(v) << ", ";
    tp<Ty, N + 1, L>::print(os, v);
  }
};
template <typename Ty, unsigned N> struct tp<Ty, N, N> {
  static void print(ostream &os, const Ty &value) { os << get<N>(value); }
};
} // namespace aux
template <typename... Tys>
ostream &operator<<(ostream &os, const tuple<Tys...> &t) {
  os << "{";
  aux::tp<tuple<Tys...>, 0, sizeof...(Tys) - 1>::print(os, t);
  os << "}";
  return os;
}

template <typename A, size_t N, typename T>
inline void Fill(A (&array)[N], const T &val) {
  std::fill((T *)array, (T *)(array + N), val);
}

void dump_func() { DUMPOUT << endl; }
template <class Head, class... Tail>
void dump_func(Head &&head, Tail &&...tail) {
  DUMPOUT << head;
  if (sizeof...(Tail) == 0) {
    DUMPOUT << " ";
  } else {
    DUMPOUT << ", ";
  }
  dump_func(std::move(tail)...);
}

#define PI 3.14159265358979323846
#define EPS 1e-11
#define FOR(i, a, b) for (int i = (a); i < (b); ++i)
#define REP(i, n) FOR(i, 0, n)
#define all(x) (x).begin(), (x).end()
#define SZ(x) ((int)(x).size())
#define fake false

const int di[] = {0, -1, 0, 1};
const int dj[] = {1, 0, -1, 0};

void print_board(const vector<vector<int>> &v) {
  REP(i, v.size()) {
    REP(j, v[i].size()) {
      if (v[i][j] == -1)
        printf(" .");
      else if (v[i][j] == -2)
        printf(" #");
      else
        printf("%2d", v[i][j]);
    }
    printf("\\n");
  }
}

int main() {
  // clock_t start, end;
  // start = clock();

  cin.tie(0);
  ios::sync_with_stdio(false);

  int H, W, N;
  cin >> H >> W >> N;

  vector<string> S(H);
  cin >> S;

  vector<pii> points(N + 1);

  const int space = -1;
  const int block = -2;

  vector<vector<int>> board(H, vector<int>(W, space));

  REP(i, H) REP(j, W) {
    if (S[i][j] == 'S')
      points[0] = pii(i, j);
    else if ('0' <= S[i][j] && S[i][j] <= '9')
      points[S[i][j] - '0'] = pii(i, j);
    else if (S[i][j] == 'X')
      board[i][j] = block;
  }

  int ans = 0;
  REP(k, N) {
    pii from = points[k], to = points[k + 1];

    vector<vector<int>> btmp(board);

    queue<pii> qu;
    qu.push(from);
    btmp[from.first][from.second] = 0;

    while (!qu.empty()) {
      pii p = qu.front();
      qu.pop();
      int i = p.first, j = p.second;

      int step = btmp[i][j];
      if (p == to) {
        ans += step;
        break;
      }

      REP(d, 4) {
        int ni = i + di[d], nj = j + dj[d];
        if (ni < 0 || H <= ni || nj < 0 || W <= nj)
          continue;
        if (btmp[ni][nj] == block)
          continue;
        if (btmp[ni][nj] >= 0)
          continue;
        btmp[ni][nj] = step + 1;
        qu.push(pii(ni, nj));
      }
    }
  }
  cout << ans << endl;

  // end = clock();
  // printf("%d msec.\\n", end - start);

  return 0;
}