#include <algorithm>
#include <bitset>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <deque>
#include <functional>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>

using namespace std;

inline int toInt(string s) {
  int v;
  istringstream sin(s);
  sin >> v;
  return v;
}
template <class T> inline string toString(T x) {
  ostringstream sout;
  sout << x;
  return sout.str();
}
template <class T> inline T sqr(T x) { return x * x; }

typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<string> vs;
typedef pair<int, int> pii;
typedef long long ll;

#define all(a) (a).begin(), (a).end()
#define rall(a) (a).rbegin(), (a).rend()
#define pb push_back
#define mp make_pair
#define each(i, c)                                                             \\
  for (typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define exist(s, e) ((s).find(e) != (s).end())
#define range(i, a, b) for (int i = (a); i < (b); ++i)
#define rep(i, n) range(i, 0, n)
#define clr(a, b) memset((a), (b), sizeof(a))
#define dump(x) cerr << #x << " = " << (x) << endl;
#define debug(x)                                                               \\
  cerr << #x << " = " << (x) << " (L" << __LINE__ << ")"                       \\
       << " " << __FILE__ << endl;

const double eps = 1e-10;
const double pi = acos(-1.0);
const ll inf = 1LL << 62;

struct node {
  int x;
  int y;
  int c;
};

bool check[1010][1010];
string maze[1010];
int hmax = 1;

int main(void) {
  int H, W, n;
  cin >> H >> W >> n;
  rep(i, H) cin >> maze[i];
  node init;
  rep(i, H) rep(j, W) {
    check[i][j] = false;
    if (maze[i][j] == 'S') {
      init.x = j;
      init.y = i;
      init.c = 0;
    }
  }
  int ans = 0;
  rep(j, n) {
    //	cout << j << endl;
    queue<node> q;
    q.push(init);
    int dx[4] = {1, 0, -1, 0};
    int dy[4] = {0, 1, 0, -1};
    while (!q.empty()) {
      node cur;
      cur = q.front();
      q.pop();
      // テァツ渉セテ・ツ慊ィテ、ツスツ催ァツスツョテ」ツ?ョテ・ツ按、テ・ツョツ堙・ツ?ヲテァツ青?
      if (check[cur.y][cur.x])
        continue;
      if (hmax == (maze[cur.y][cur.x] - '0')) {
        ans += cur.c;
        hmax++;
        break;
      }
      // テ」ツ??ヲツャツ。テ」ツ?ョテァツ環カテヲツ?凝」ツ?クテ」ツ?ョテゥツ?キテァツァツサ
      rep(i, 4) {
        node next;
        next.x = cur.x + dx[i];
        next.y = cur.y + dy[i];
        next.c = cur.c + 1;
        if (0 <= next.x && next.x < W && 0 <= next.y && next.y < H &&
            maze[next.y][next.x] != 'X')
          q.push(next);
      }
    }
    rep(k, H) rep(l, W) {
      check[k][l] = false;
      if (maze[k][l] == ('0' + (hmax - 1))) {
        init.x = l;
        init.y = k;
        init.c = 0;
      }
    }
  }
  cout << ans << endl;
  return 0;
}

#include <algorithm>
#include <bitset>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <deque>
#include <functional>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>

using namespace std;

inline int toInt(string s) {
  int v;
  istringstream sin(s);
  sin >> v;
  return v;
}
template <class T> inline string toString(T x) {
  ostringstream sout;
  sout << x;
  return sout.str();
}
template <class T> inline T sqr(T x) { return x * x; }

typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<string> vs;
typedef pair<int, int> pii;
typedef long long ll;

#define all(a) (a).begin(), (a).end()
#define rall(a) (a).rbegin(), (a).rend()
#define pb push_back
#define mp make_pair
#define each(i, c)                                                             \\
  for (typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define exist(s, e) ((s).find(e) != (s).end())
#define range(i, a, b) for (int i = (a); i < (b); ++i)
#define rep(i, n) range(i, 0, n)
#define clr(a, b) memset((a), (b), sizeof(a))
#define dump(x) cerr << #x << " = " << (x) << endl;
#define debug(x)                                                               \\
  cerr << #x << " = " << (x) << " (L" << __LINE__ << ")"                       \\
       << " " << __FILE__ << endl;

const double eps = 1e-10;
const double pi = acos(-1.0);
const ll inf = 1LL << 62;
const int INF = 1 << 30;
struct node {
  int x;
  int y;
  int c;
  bool operator<(node a) const { return c < a.c; }
  bool operator>(node a) const { return c > a.c; }
};

int dis[1010][1010];
int nx[10];
int ny[10];
string maze[1010];
int hmax = 1;

int main(void) {
  int H, W, n;
  cin >> H >> W >> n;
  rep(i, H) cin >> maze[i];
  node init;
  rep(i, H) rep(j, W) {
    if (maze[i][j] == 'S') {
      nx[0] = j;
      ny[0] = i;
    } else if (isdigit(maze[i][j])) {
      nx[maze[i][j] - '0'] = j;
      ny[maze[i][j] - '0'] = i;
    }
  }
  int ans = 0;
  rep(j, n) {
    rep(k, H) rep(l, W) dis[k][l] = INF;
    init.x = nx[j];
    init.y = ny[j];
    init.c = 0;
    priority_queue<node, vector<node>, greater<node>> q;
    q.push(init);
    int dx[4] = {1, 0, -1, 0};
    int dy[4] = {0, 1, 0, -1};
    while (!q.empty()) {
      node cur;
      cur = q.top();
      q.pop();
      // テァツ渉セテ・ツ慊ィテ、ツスツ催ァツスツョテ」ツ?ョテ・ツ按、テ・ツョツ堙・ツ?ヲテァツ青?
      if (dis[cur.y][cur.x] <= cur.c)
        continue;
      else
        dis[cur.y][cur.x] = cur.c;
      if (hmax == (maze[cur.y][cur.x] - '0')) {
        ans += cur.c;
        hmax++;
        break;
      }
      // テ」ツ??ヲツャツ。テ」ツ?ョテァツ環カテヲツ?凝」ツ?クテ」ツ?ョテゥツ?キテァツァツサ
      rep(i, 4) {
        node next;
        next.x = cur.x + dx[i];
        next.y = cur.y + dy[i];
        next.c = cur.c + 1;
        if (0 <= next.x && next.x < W && 0 <= next.y && next.y < H &&
            maze[next.y][next.x] != 'X')
          q.push(next);
      }
    }
  }
  cout << ans << endl;
  return 0;
}


#include <bits/stdc++.h>

using namespace std;

#define all(c) ((c).begin()), ((c).end())
#define dump(c) cerr << "> " << #c << " = " << (c) << endl;
#define iter(c) __typeof((c).begin())
#define tr(i, c) for (iter(c) i = (c).begin(); i != (c).end(); i++)
#define REP(i, a, b) for (int i = a; i < (int)(b); i++)
#define rep(i, n) REP(i, 0, n)
#define mp make_pair
#define fst first
#define snd second
#define pb push_back

typedef unsigned int uint;
typedef long long ll;
typedef unsigned long long ull;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<double> vd;
typedef vector<vd> vvd;
typedef vector<string> vs;
typedef pair<int, int> pii;

const int INF = 1 << 29;
const double EPS = 1e-10;

double zero(double d) { return d < EPS ? 0.0 : d; }

template <typename T1, typename T2>
ostream &operator<<(ostream &os, const pair<T1, T2> &p) {
  return os << '(' << p.first << ',' << p.second << ')';
}

template <typename T> ostream &operator<<(ostream &os, const vector<T> &a) {
  os << '[';
  rep(i, a.size()) os << (i ? " " : "") << a[i];
  return os << ']';
}

// to avoid error on mingw
string toString(int i) {
  stringstream ss;
  ss << i;
  return ss.str();
}

const int M = 1000000007;
// a^k
ll fpow(ll a, ll k, int M) {
  ll res = 1ll;
  ll x = a;
  while (k != 0) {
    if ((k & 1) == 1)
      res = (res * x) % M;
    x = (x * x) % M;
    k >>= 1;
  }
  return res;
}

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

int main() {
  cout.setf(ios::fixed, ios::floatfield);
  cout.precision(8);
  ios_base::sync_with_stdio(false);

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

  int a[H][W];
  memset(a, 0, sizeof(a));
  bool vis[H][W];
  memset(vis, 0, sizeof(vis));

  int start = 0;
  rep(r, H) {
    string t;
    cin >> t;
    rep(c, W) {
      if (t[c] == 'S')
        start = r * W + c;
      else if (t[c] == 'X')
        a[r][c] = -1;
      else if (t[c] != '.')
        a[r][c] = t[c] - '0';
    }
  }

  queue<pii> que;
  que.push(mp(start, 0));

  int target = 1;
  int ans = 0;
  while (!que.empty()) {
    pii t = que.front();
    que.pop();
    int r = t.first / W;
    int c = t.first % W;
    int dist = t.second;

    vis[r][c] = true;

    // cerr << r << " " << c << " " << dist << " " << ans << endl;

    if (a[r][c] == target) {
      ans += dist;

      if (target == N)
        break;
      target++;

      que = queue<pii>();
      start = r * W + c;
      que.push(mp(start, 0));

      memset(vis, 0, sizeof(vis));
      vis[r][c] = true;
      continue;
    }

    rep(i, 4) {
      int nr = r + dy[i];
      int nc = c + dx[i];

      if (nr < 0 || H <= nr || nc < 0 || W <= nc || a[nr][nc] == -1)
        continue;

      if (!vis[nr][nc])
        que.push(mp(nr * W + nc, dist + 1));
    }
  }

  cout << ans << endl;

  return 0;
}

#include <bits/stdc++.h>

using namespace std;

#define all(c) ((c).begin()), ((c).end())
#define dump(c) cerr << "> " << #c << " = " << (c) << endl;
#define iter(c) __typeof((c).begin())
#define tr(i, c) for (iter(c) i = (c).begin(); i != (c).end(); i++)
#define REP(i, a, b) for (int i = a; i < (int)(b); i++)
#define rep(i, n) REP(i, 0, n)
#define mp make_pair
#define fst first
#define snd second
#define pb push_back

typedef unsigned int uint;
typedef long long ll;
typedef unsigned long long ull;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<double> vd;
typedef vector<vd> vvd;
typedef vector<string> vs;
typedef pair<int, int> pii;

const int INF = 1 << 29;
const double EPS = 1e-10;

double zero(double d) { return d < EPS ? 0.0 : d; }

template <typename T1, typename T2>
ostream &operator<<(ostream &os, const pair<T1, T2> &p) {
  return os << '(' << p.first << ',' << p.second << ')';
}

template <typename T> ostream &operator<<(ostream &os, const vector<T> &a) {
  os << '[';
  rep(i, a.size()) os << (i ? " " : "") << a[i];
  return os << ']';
}

// to avoid error on mingw
string toString(int i) {
  stringstream ss;
  ss << i;
  return ss.str();
}

const int M = 1000000007;
// a^k
ll fpow(ll a, ll k, int M) {
  ll res = 1ll;
  ll x = a;
  while (k != 0) {
    if ((k & 1) == 1)
      res = (res * x) % M;
    x = (x * x) % M;
    k >>= 1;
  }
  return res;
}

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

int main() {
  cout.setf(ios::fixed, ios::floatfield);
  cout.precision(8);
  ios_base::sync_with_stdio(false);

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

  int a[H][W];
  memset(a, 0, sizeof(a));
  int vis[H][W];
  memset(vis, -1, sizeof(vis));

  int start = 0;
  rep(r, H) {
    string t;
    cin >> t;
    rep(c, W) {
      if (t[c] == 'S')
        start = r * W + c;
      else if (t[c] == 'X')
        a[r][c] = -1;
      else if (t[c] != '.')
        a[r][c] = t[c] - '0';
    }
  }

  int ans = 0;

  REP(target, 1, N + 1) {
    queue<int> que;
    que.push(start);

    memset(vis, -1, sizeof(vis));
    vis[start / W][start % W] = 0;

    while (!que.empty()) {
      int t = que.front();
      que.pop();
      int r = t / W;
      int c = t % W;

      if (a[r][c] == target) {
        ans += vis[r][c];
        start = r * W + c;
        break;
      }

      rep(i, 4) {
        int nr = r + dy[i];
        int nc = c + dx[i];

        if (nr < 0 || H <= nr || nc < 0 || W <= nc || a[nr][nc] == -1 ||
            vis[nr][nc] != -1)
          continue;

        vis[nr][nc] = vis[r][c] + 1;

        // cerr << r << " " << c <<  " : " << a[r][c] <<  endl;

        que.push(nr * W + nc);
      }
    }
  }

  cout << ans << endl;

  return 0;
}


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

#define INF (1e+9)
#define LLINF (1e+18)
#define LL long long

using namespace std;

typedef struct info {
  int nx;
  int ny;
  int cost;
  int target;
  info(int a, int b, int c, int d) {
    nx = a;
    ny = b;
    cost = c;
    target = d;
  }
} info;

bool isNumChar(char c) {
  if ((0 <= c - 48) && (c - 48 <= 9))
    return true;
  return false;
}

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

int W, H;
int N;

int sx[16] = {0};
int sy[16] = {0};

char field[1024][1024] = {""};
int record[1024][1024][12] = {0};
bool flag[16] = {false};

queue<info> que;

int ans;

int recordReset() {
  for (int i = 0; i < 1024; i++) {
    for (int j = 0; j < 1024; j++) {
      for (int k = 0; k < 16; k++) {
        record[i][j][k] = INF;
      }
    }
  }
}

int bfs() {
  info now(0, 0, 0, 0);
  info next(0, 0, 0, 0);
  for (int i = 0; i < N; i++) {
    next = info(sx[i], sy[i], 0, i + 1);
    que.push(next);
  }

  recordReset();
  while (!que.empty()) {
    now = que.front();
    que.pop();
    if (!flag[now.target]) {
      // printf("###(%d,%d):::cost<%d>:::target<%d>\\n",now.nx,now.ny,now.cost,now.target);
      if (record[now.nx][now.ny][now.target] > now.cost) {
        record[now.nx][now.ny][now.target] = now.cost;
        if ((sx[now.target] == now.nx) && (sy[now.target] == now.ny)) {
          flag[now.target] = true;
          // printf("###target<%d> completed\\n",now.target);
          ans += record[now.nx][now.ny][now.target];
        } else {
          switch (field[now.nx][now.ny]) {
          case 'X':
            break;
          default:
            for (int i = 0; i < 4; i++) {
              next = info(now.nx + dx[i], now.ny + dy[i], now.cost + 1,
                          now.target);
              que.push(next);
            }
            break;
          }
        }
      }
    }
  }
}

int main(void) {
  // while(true){
  scanf("%d%d", &H, &W);
  scanf("%d", &N);
  // if((W == 0)&&(H == 0))break;

  ans = 0;

  // Reset Field
  for (int i = 0; i < 1024; i++) {
    for (int j = 0; j < 1024; j++) {
      field[j][i] = 'X';
    }
  }

  // Reset Flag
  for (int i = 0; i < 16; i++) {
    flag[i] = false;
  }

  // Reading Data
  for (int i = 1; i <= H; i++) {
    scanf(" ");
    for (int j = 1; j <= W; j++) {
      scanf("%c", &field[j][i]);
      if (isNumChar(field[j][i])) {
        sx[field[j][i] - 48] = j;
        sy[field[j][i] - 48] = i;
        // printf("###<%d>(%d,%d)\\n",field[j][i] - 48,sx[field[j][i] -
        // 48],sy[field[j][i] - 48]);

      } else if (field[j][i] == 'S') {
        sx[0] = j;
        sy[0] = i;
        // printf("###<S>(%d,%d)\\n",j,i);
      }
    }
  }

  // DBG
  /*for(int i = 0;i < N;i++){
          printf("<%d>(%d,%d)\\n",i,sx[i],sy[i]);
  }*/

  bfs();

  printf("%d\\n", ans);
  //}

  return 0;
}

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

#define INF (1e+9)
#define LLINF (1e+18)
#define LL long long

using namespace std;

typedef struct info {
  int nx;
  int ny;
  int cost;
  int target;
  info(int a, int b, int c, int d) {
    nx = a;
    ny = b;
    cost = c;
    target = d;
  }
} info;

bool isNumChar(char c) {
  if ((0 <= c - 48) && (c - 48 <= 9))
    return true;
  return false;
}

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

int W, H;
int N;

int sx[16] = {0};
int sy[16] = {0};

char field[1024][1024] = {""};
int record[1024][1024][12] = {0};
bool flag[16] = {false};

queue<info> que;

int ans;

int recordReset() {
  for (int i = 0; i < 1024; i++) {
    for (int j = 0; j < 1024; j++) {
      for (int k = 0; k < 12; k++) {
        record[i][j][k] = INF;
      }
    }
  }
}

int bfs() {
  info now(0, 0, 0, 0);
  info next(0, 0, 0, 0);
  for (int i = 0; i < N; i++) {
    next = info(sx[i], sy[i], 0, i + 1);
    que.push(next);
  }

  recordReset();
  while (!que.empty()) {
    now = que.front();
    que.pop();
    if (!flag[now.target]) {
      // printf("###(%d,%d):::cost<%d>:::target<%d>\\n",now.nx,now.ny,now.cost,now.target);
      if (record[now.nx][now.ny][now.target] > now.cost) {
        record[now.nx][now.ny][now.target] = now.cost;
        if ((sx[now.target] == now.nx) && (sy[now.target] == now.ny)) {
          flag[now.target] = true;
          // printf("###target<%d> completed\\n",now.target);
          ans += record[now.nx][now.ny][now.target];
        } else {
          switch (field[now.nx][now.ny]) {
          case 'X':
            break;
          default:
            for (int i = 0; i < 4; i++) {
              next = info(now.nx + dx[i], now.ny + dy[i], now.cost + 1,
                          now.target);
              que.push(next);
            }
            break;
          }
        }
      }
    }
  }
}

int main(void) {
  // while(true){
  scanf("%d%d", &H, &W);
  scanf("%d", &N);
  // if((W == 0)&&(H == 0))break;

  ans = 0;

  // Reset Field
  for (int i = 0; i < 1024; i++) {
    for (int j = 0; j < 1024; j++) {
      field[j][i] = 'X';
    }
  }

  // Reset Flag
  for (int i = 0; i < 16; i++) {
    flag[i] = false;
  }

  // Reading Data
  for (int i = 1; i <= H; i++) {
    scanf(" ");
    for (int j = 1; j <= W; j++) {
      scanf("%c", &field[j][i]);
      if (isNumChar(field[j][i])) {
        sx[field[j][i] - 48] = j;
        sy[field[j][i] - 48] = i;
        // printf("###<%d>(%d,%d)\\n",field[j][i] - 48,sx[field[j][i] -
        // 48],sy[field[j][i] - 48]);

      } else if (field[j][i] == 'S') {
        sx[0] = j;
        sy[0] = i;
        // printf("###<S>(%d,%d)\\n",j,i);
      }
    }
  }

  // DBG
  /*for(int i = 0;i < N;i++){
          printf("<%d>(%d,%d)\\n",i,sx[i],sy[i]);
  }*/

  bfs();

  printf("%d\\n", ans);
  //}

  return 0;
}


#define _CRT_SECURE_NO_WARNINGS
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <functional>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <utility>
#include <vector>

using namespace std;

typedef long long LL;
typedef vector<int> Array;
typedef pair<int, int> P;

const int INF = 1 << 29;
const LL MOD = 100000;
#define rep(i, n) for (int i = 0; i < (int)n; ++i)
#define all(c) (c).begin(), (c).end()

struct edge {
  int to, cost;
  edge(int t, int c) : to(t), cost(c) {}
};

int main() {
  // while (cin >> n)
  stringstream ss;
  // ss << "result" << i + 1 << ".txt";
  // FILE* fp_out = freopen(ss.str().c_str(), "w", stdout);

  int h, w, n;
  while (cin >> h >> w >> n && h) {
    vector<vector<char>> stage(h, vector<char>(w));
    vector<P> cheese(n + 1);
    rep(i, h) rep(j, w) {
      char c;
      cin >> c;
      stage[i][j] = c;
      if (c == 'S')
        cheese[0] = P(i, j);
      if (1 <= c - '0' && c - '0' <= 9)
        cheese[c - '0'] = P(i, j);
    }

    int ans = 0;
    vector<int> dr = {-1, 0, 1, 0};
    vector<int> dc = {0, 1, 0, -1};
    rep(i, n) {
      P from = cheese[i], to = cheese[i + 1];
      typedef pair<P, int> PI;
      queue<PI> que;
      vector<vector<bool>> visited(h, vector<bool>(w));
      que.emplace(from, 0);
      while (!que.empty()) {
        PI pi = que.front();
        que.pop();
        P p = pi.first;
        int len = pi.second;

        if (p == to) {
          ans += len;
          break;
        }

        visited[p.first][p.second] = true;
        rep(k, 4) {
          int nr = dr[k] + p.first, nc = dc[k] + p.second;
          if (nr < 0 || nr >= h || nc < 0 || nc >= w || stage[nr][nc] == 'X' ||
              visited[nr][nc])
            continue;

          que.emplace(P(nr, nc), len + 1);
        }
      }
    }

    cout << ans << endl;
  }

  return 0;
}

#define _CRT_SECURE_NO_WARNINGS
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <functional>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <utility>
#include <vector>

using namespace std;

typedef long long LL;
typedef vector<int> Array;
typedef pair<int, int> P;

const int INF = 1 << 29;
const LL MOD = 100000;
#define rep(i, n) for (int i = 0; i < (int)n; ++i)
#define all(c) (c).begin(), (c).end()

struct edge {
  int to, cost;
  edge(int t, int c) : to(t), cost(c) {}
};

int main() {
  // while (cin >> n)
  stringstream ss;
  // ss << "result" << i + 1 << ".txt";
  // FILE* fp_out = freopen(ss.str().c_str(), "w", stdout);

  int h, w, n;
  while (cin >> h >> w >> n && h) {
    vector<vector<char>> stage(h, vector<char>(w));
    vector<P> cheese(n + 1);
    rep(i, h) rep(j, w) {
      char c;
      cin >> c;
      stage[i][j] = c;
      if (c == 'S')
        cheese[0] = P(i, j);
      if (1 <= c - '0' && c - '0' <= 9)
        cheese[c - '0'] = P(i, j);
    }

    int ans = 0;
    vector<int> dr = {-1, 0, 1, 0};
    vector<int> dc = {0, 1, 0, -1};
    rep(i, n) {
      P from = cheese[i], to = cheese[i + 1];
      typedef pair<P, int> PI;
      queue<PI> que;
      vector<vector<bool>> visited(h, vector<bool>(w));
      que.emplace(from, 0);
      while (!que.empty()) {
        PI pi = que.front();
        que.pop();
        P p = pi.first;
        int len = pi.second;

        if (p == to) {
          ans += len;
          break;
        }

        rep(k, 4) {
          int nr = dr[k] + p.first, nc = dc[k] + p.second;
          if (nr < 0 || nr >= h || nc < 0 || nc >= w || stage[nr][nc] == 'X' ||
              visited[nr][nc])
            continue;

          visited[nr][nc] = true;
          que.emplace(P(nr, nc), len + 1);
        }
      }
    }

    cout << ans << endl;
  }

  return 0;
}


#include <iostream>
#include <map>
#include <queue>

#define rep(i, a, b) for (int i = (a); (i) < (b); (i)++)
#define ft first
#define sd second

using namespace std;

char m[1000][1000];
int dis[1000][1000];
queue<pair<int, int>> state;

int main() {
  int h, w, n;

  cin >> h >> w >> n;

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

  pair<int, int> p;
  p.ft = sx;
  p.sd = sy;

  rep(i, 0, h) {
    rep(j, 0, w) { dis[j][i] = -1; }
  }
  dis[sx][sy] = 0;
  state.push(p);

  int dx[4] = {-1, 0, 1, 0};
  int dy[4] = {0, -1, 0, 1};
  int map2[1000][1000];
  for (int lp = 1; lp <= n; lp++) {
    rep(i, 0, h) {
      rep(j, 0, w) { map2[j][i] = 0; }
    }

    map2[sx][sy] = 1;
    while (state.size()) {
      pair<int, int> now = state.front();
      state.pop();
      if (m[now.ft][now.sd] - '0' == lp) {
        sx = now.ft;
        sy = now.sd;
        break;
      }

      rep(lp2, 0, 4) {
        int x = now.ft + dx[lp2];
        int y = now.sd + dy[lp2];

        if (x < 0 || w <= x || y < 0 || h <= y)
          continue;
        if (map2[x][y] == 0 && m[x][y] != 'X') {
          state.push(make_pair(x, y));
          dis[x][y] = dis[now.ft][now.sd] + 1;
          map2[now.ft][now.sd] = 1;
        }
      }
    }
    while (state.size())
      state.pop();

    state.push(make_pair(sx, sy));
  }

  cout << dis[sx][sy] << endl;
  return 0;
}

#include <iostream>
#include <map>
#include <queue>

#define rep(i, a, b) for (int i = (a); (i) < (b); (i)++)
#define ft first
#define sd second

using namespace std;

char m[1000][1000];
int dis[1000][1000];
queue<pair<int, int>> state;

int main() {
  int h, w, n;

  cin >> h >> w >> n;

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

  pair<int, int> p;
  p.ft = sx;
  p.sd = sy;

  rep(i, 0, h) {
    rep(j, 0, w) { dis[j][i] = -1; }
  }
  dis[sx][sy] = 0;
  state.push(p);

  int dx[4] = {-1, 0, 1, 0};
  int dy[4] = {0, -1, 0, 1};
  int map2[1000][1000];
  for (int lp = 1; lp <= n; lp++) {
    rep(i, 0, h) {
      rep(j, 0, w) { map2[j][i] = 0; }
    }

    map2[sx][sy] = 1;
    while (state.size()) {
      pair<int, int> now = state.front();
      state.pop();
      if (m[now.ft][now.sd] - '0' == lp) {
        sx = now.ft;
        sy = now.sd;
        break;
      }

      rep(lp2, 0, 4) {
        int x = now.ft + dx[lp2];
        int y = now.sd + dy[lp2];

        if (x < 0 || w <= x || y < 0 || h <= y)
          continue;
        if (map2[x][y] == 0 && m[x][y] != 'X') {
          state.push(make_pair(x, y));
          dis[x][y] = dis[now.ft][now.sd] + 1;
          map2[x][y] = 1;
        }
      }
    }
    while (state.size())
      state.pop();

    state.push(make_pair(sx, sy));
  }

  cout << dis[sx][sy] << endl;
  return 0;
}


#include <climits>
#include <cstdlib>
#include <iostream>
#include <queue>
using namespace std;
int d[1000][1000];
char input[1000][1000];
bool visited[1000][1000];
int H, W, N, S_x, S_y, answer = 0;
const int dirx[] = {0, -1, 0, 1};
const int diry[] = {1, 0, -1, 0};
int now = '1';
int D[10];
queue<char> q;
void BFS();
void clean();
int main() {
  int i, j;
  char ch;
  cin >> H >> W >> N;
  for (i = 0; i < H * W; i++) {
    cin >> ch;
    input[i % W][i / W] = ch;
    d[i % W][i / W] = 0;
    if (ch == 'S') {
      S_x = i % W;
      S_y = i / W;
    }
  }
  while (now <= N + 48) {
    BFS();
    now++;
  }
  for (i = 1; i <= N; i++)
    answer += D[i];
  cout << answer << endl;
}
void BFS() {
  int x, y, k, mx, my;
  q.push(S_x);
  q.push(S_y);
  visited[S_x][S_y] = true;
  while (!q.empty()) {
    x = q.front();
    q.pop();
    y = q.front();
    q.pop();
    for (k = 0; k < 4; k++) {
      mx = x + dirx[k];
      my = y + diry[k];
      if (mx < W && mx >= 0 && my < H && my >= 0) {
        if (input[mx][my] != 'X' && !visited[mx][my]) {
          q.push(mx);
          q.push(my);
          d[mx][my] = d[x][y] + 1;
          if (input[mx][my] == (char)now) {
            S_x = mx;
            S_y = my;
            D[now - 48] = d[mx][my];
          }
          visited[mx][my] = true;
        }
      }
    }
  }
  clean();
}
void clean() {
  int i, j;
  for (i = 0; i <= W; i++)
    for (j = 0; j <= H; j++) {
      visited[i][j] = false;
      d[i][j] = 0;
    }
}

#include <climits>
#include <cstdlib>
#include <iostream>
#include <queue>
using namespace std;
int d[1111][1111];
char input[1111][1111];
bool visited[1111][1111];
int H, W, N, S_x, S_y, answer = 0;
const int dirx[] = {0, -1, 0, 1};
const int diry[] = {1, 0, -1, 0};
int now = '1';
int D[11];
queue<int> q;
void BFS();
void clean();
int main() {
  int i, j;
  char ch;
  cin >> H >> W >> N;
  for (i = 0; i < H * W; i++) {
    cin >> ch;
    input[i % W][i / W] = ch;
    d[i % W][i / W] = 0;
    if (ch == 'S') {
      S_x = i % W;
      S_y = i / W;
    }
  }
  while (now <= N + 48) {
    BFS();
    now++;
  }
  for (i = 1; i <= N; i++) {
    answer += D[i];
  }
  cout << answer << endl;
}
void BFS() {
  int x, y, k, mx, my;
  q.push(S_x);
  q.push(S_y);
  visited[S_x][S_y] = true;
  while (!q.empty()) {
    x = q.front();
    q.pop();
    y = q.front();
    q.pop();
    for (k = 0; k < 4; k++) {
      mx = x + dirx[k];
      my = y + diry[k];
      if (mx < W && mx >= 0 && my < H && my >= 0) {
        if (input[mx][my] != 'X' && !visited[mx][my]) {
          q.push(mx);
          q.push(my);
          d[mx][my] = d[x][y] + 1;
          if (input[mx][my] == (char)now) {
            S_x = mx;
            S_y = my;
            D[now - 48] = d[mx][my];
          }
          visited[mx][my] = true;
        }
      }
    }
  }
  clean();
}
void clean() {
  int i, j;
  for (i = 0; i < W; i++)
    for (j = 0; j < H; j++) {
      visited[i][j] = false;
      d[i][j] = 0;
    }
}


#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <queue>
#include <stack>
#include <string>
#define INF 100000000
using namespace std;

struct coor {
  int x, y;
};

char map[1002][1002];
int tim[1002][1002];
int vis[1002][1002];
int dx[4] = {0, 1, 0, -1};
int dy[4] = {1, 0, -1, 0};
int h, w, n;
coor s;
coor fac[10];
int phy;
int ans;

int bfs(coor fa) {
  coor next;
  coor now;
  queue<coor> q;
  q.push(s);
  vis[s.x][s.y] = 1;
  while (!q.empty()) {
    now = q.front();
    q.pop();
    if (now.x == fa.x && now.y == fa.y) {
      break;
    }
    vis[now.x][now.y] = 1;
    for (int i = 0; i < 4; i++) {
      next.x = now.x + dx[i];
      next.y = now.y + dy[i];
      if (map[next.x][next.y] != 'X' && next.x >= 0 && next.x < h &&
          next.y >= 0 && next.y < w && !vis[next.x][next.y]) {
        tim[next.x][next.y] = tim[now.x][now.y] + 1;
        q.push(next);
      }
    }
  }
  return tim[fa.x][fa.y];
}

void timeinit(coor st) {
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      if (map[i][j] != 'X')
        tim[i][j] = INF;
    }
  }
  tim[st.x][st.y] = 0;
}
int main() {
  while (~scanf("%d%d%d", &h, &w, &n)) {
    getchar();
    for (int i = 0; i < h; i++) {
      for (int j = 0; j < w; j++) {
        scanf("%c", &map[i][j]);
        tim[i][j] = INF;
        if (map[i][j] == 'S') {
          map[i][j] = '.';
          s.x = i;
          s.y = j;
        }
        if (isdigit(map[i][j])) {
          fac[map[i][j] - '0'].x = i;
          fac[map[i][j] - '0'].y = j;
        }
      }
      getchar();
    }

    phy = 1;
    tim[s.x][s.y] = 0;
    ans = 0;
    for (int i = 1; i <= n; i++) {
      memset(vis, 0, sizeof(vis));
      ans += bfs(fac[i]);
      s.x = fac[i].x;
      s.y = fac[i].y;
      timeinit(s);
    }
    printf("%d\\n", ans);
  }
  return 0;
}

#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <queue>
#include <stack>
#include <string>
#define INF 100000000
using namespace std;

struct coor {
  int x, y;
};

char map[1002][1002];
int tim[1002][1002];
int dx[4] = {0, 1, 0, -1};
int dy[4] = {1, 0, -1, 0};
int h, w, n;
coor s;
coor fac[10];
int phy;
int ans;

int bfs(coor fa) {
  coor next;
  coor now;
  queue<coor> q;
  q.push(s);
  while (!q.empty()) {
    now = q.front();
    q.pop();
    if (now.x == fa.x && now.y == fa.y) {
      break;
    }
    for (int i = 0; i < 4; i++) {
      next.x = now.x + dx[i];
      next.y = now.y + dy[i];
      if (map[next.x][next.y] != 'X' && next.x >= 0 && next.x < h &&
          next.y >= 0 && next.y < w && tim[next.x][next.y] == INF) {
        tim[next.x][next.y] = tim[now.x][now.y] + 1;
        q.push(next);
      }
    }
  }
  return tim[fa.x][fa.y];
}

void timeinit(coor st) {
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      if (map[i][j] != 'X')
        tim[i][j] = INF;
    }
  }
  tim[st.x][st.y] = 0;
}
int main() {
  while (~scanf("%d%d%d", &h, &w, &n)) {
    getchar();
    for (int i = 0; i < h; i++) {
      for (int j = 0; j < w; j++) {
        scanf("%c", &map[i][j]);
        tim[i][j] = INF;
        if (map[i][j] == 'S') {
          map[i][j] = '.';
          s.x = i;
          s.y = j;
        }
        if (isdigit(map[i][j])) {
          fac[map[i][j] - '0'].x = i;
          fac[map[i][j] - '0'].y = j;
        }
      }
      getchar();
    }

    phy = 1;
    tim[s.x][s.y] = 0;
    ans = 0;
    for (int i = 1; i <= n; i++) {
      ans += bfs(fac[i]);
      s.x = fac[i].x;
      s.y = fac[i].y;
      timeinit(s);
    }
    printf("%d\\n", ans);
  }
  return 0;
}


#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <functional>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>

using namespace std;

#define rep(i, n) for (int i = 0; i < (n); i++)
#define repc(i, s, e) for (int i = (s); i < (e); i++)
#define pb(n) push_back((n))
#define mp(n, m) make_pair((n), (m))
#define all(r) r.begin(), r.end()
#define fi first
#define se second

typedef long long ll;
typedef vector<int> vi;
typedef vector<vi> vii;
typedef vector<ll> vl;
typedef vector<vl> vll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;

const int INF = 1e9;

int dx[] = {-1, 0, 1, 0};
int dy[] = {0, -1, 0, 1};
int h, w, n;
vector<string> s;

int bfs(pii st, pii g) {
  vector<vector<int>> v(h, vi(w, 0));
  queue<pair<pii, int>> q;
  pair<pii, int> p(st, 0);
  q.push(p);
  while (!q.empty()) {
    p = q.front();
    q.pop();
    v[p.fi.fi][p.fi.se] = 1;
    if (g == p.fi) {
      return p.se;
    }
    for (int i = 0; i < 4; i++) {
      int y = p.fi.fi + dy[i], x = p.fi.se + dx[i];
      if (y < 0 || y >= h || x < 0 || x >= w || s[y][x] == 'X' || v[y][x])
        continue;
      q.push(pair<pii, int>(pii(y, x), p.se + 1));
    }
  }
  return -1;
}

int main() {
  cin >> h >> w >> n;
  s = vector<string>(h);
  rep(i, h) cin >> s[i];
  vector<pii> p(n + 1);
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      if (s[i][j] == 'S') {
        p[0] = pii(i, j);
      } else if (s[i][j] >= '1' && s[i][j] <= '9') {
        p[s[i][j] - '0'] = pii(i, j);
      }
    }
  }

  int ans = 0;
  for (int i = 0; i < n; i++) {
    ans += bfs(p[i], p[i + 1]);
  }
  cout << ans << endl;
}

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

using namespace std;

#define pb(n) push_back(n)
#define mp(n, m) make_pair(n, m)
#define fi first
#define se second
#define all(r) (r).begin(), (r).end()

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

typedef long long ll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;

typedef vector<vi> vii;

const int INF = 100000000;
const double EPS = 1e-10;
int mod = 1000000007;

int dx[] = {1, 0, -1, 0};
int dy[] = {0, 1, 0, -1};
int h, w, n;
vector<string> s;

bool outOfRange(int y, int x) {
  if (x < 0 || x >= w || y < 0 || y >= h)
    return true;
  return false;
}

int calc(int y, int x, int c, int num) {
  // cout<<y<<x<<" "<<c<<" "<<num<<endl;
  if (num == n)
    return c;
  queue<pair<int, pii>> q;
  vector<vi> v(h, vi(w, -1));
  v[y][x] = 0;
  pair<int, pii> p(c, mp(y, x));
  q.push(p);
  while (!q.empty()) {
    // cout<<"  "<<q.size()<<endl;
    p = q.front();
    q.pop();
    int tx = p.se.se, ty = p.se.fi, tc = p.fi;
    for (int i = 0; i < 4; i++) {
      int nx = tx + dx[i], ny = ty + dy[i];
      if (outOfRange(ny, nx) || s[ny][nx] == 'X' || v[ny][nx] != -1)
        continue;
      // cout<<ny<<" "<<nx<<endl;
      if (s[ny][nx] == '1' + num) {
        // q = queue<pair<int, pii> >;
        // cout<<"AAA"<<endl;
        return calc(ny, nx, tc + 1, num + 1);
      }
      // cout<<" "<<nx<<" "<<ny<<endl;
      v[ny][nx] = tc + 1;
      q.push(mp(tc + 1, mp(ny, nx)));
    }
  }
  return -1;
}

int main() {
  cin >> h >> w >> n;
  // cout<<h<<" "<<w<<" "<<n<<endl;
  s = vector<string>(h);
  rep(i, h) cin >> s[i];
  // rep(i, h) cout<<s[i]<<endl;
  // cout<<s[2][2]<<endl;
  int sx, sy;
  rep(i, h) rep(j, w) {
    if (s[i][j] == 'S') {
      sy = i;
      sx = j;
    }
  }
  // cout<<sy<<" "<<sx<<endl;
  cout << calc(sy, sx, 0, 0) << endl;
}


#include <iostream>
#include <map>
#include <queue>
#include <string>
using namespace std;
int main() {
  int h, w, n, px, py, ans;
  int field[100][100];
  int ch[100][100];
  while (cin >> h >> w >> n) {
    ans = 0;
    string s;
    for (int i = 0; i < h; i++) {
      cin >> s;
      for (int j = 0; j < w; j++) {
        if (s[j] == 'S') {
          px = j;
          py = i;
          field[j][i] = 0;
        } else if (s[j] >= '1' && s[j] <= '9') {
          field[j][i] = s[j] - '0';
        } else if (s[j] == 'X') {
          field[j][i] = -1;
        } else {
          field[j][i] = 0;
        }
      }
    }
    for (int i = 0; i < n; i++) {
      queue<pair<int, int>> play;
      play.push(make_pair(px, py));
      for (int j = 0; j < h; j++) {
        for (int k = 0; k < w; k++) {
          ch[k][j] = 0;
        }
      }
      ch[px][py] = 1;
      for (;;) {
        int x = play.front().first;
        int y = play.front().second;
        if (field[x][y] == i + 1) {
          ans += ch[x][y] - 1;
          px = x;
          py = y;
          break;
        }
        if (x > 0) {
          if (field[x - 1][y] != -1) {
            if (ch[x - 1][y] == 0) {
              play.push(make_pair(x - 1, y));
              ch[x - 1][y] = ch[x][y] + 1;
            }
          }
        }
        if (y > 0) {
          if (field[x][y - 1] != -1) {
            if (ch[x][y - 1] == 0) {
              play.push(make_pair(x, y - 1));
              ch[x][y - 1] = ch[x][y] + 1;
            }
          }
        }
        if (x < w - 1) {
          if (field[x + 1][y] != -1) {
            if (ch[x + 1][y] == 0) {
              play.push(make_pair(x + 1, y));
              ch[x + 1][y] = ch[x][y] + 1;
            }
          }
        }
        if (y < h - 1) {
          if (field[x][y + 1] != -1) {
            if (ch[x][y + 1] == 0) {
              play.push(make_pair(x, y + 1));
              ch[x][y + 1] = ch[x][y] + 1;
            }
          }
        }
        play.pop();
      }
    }
    cout << ans << endl;
  }
  return 0;
}

#include <iostream>
#include <map>
#include <queue>
#include <string>
using namespace std;
int main() {
  int h, w, n, px, py, ans;
  int field[1000][1000];
  int ch[1000][1000];
  while (cin >> h >> w >> n) {
    ans = 0;
    string s;
    for (int i = 0; i < h; i++) {
      cin >> s;
      for (int j = 0; j < w; j++) {
        if (s[j] == 'S') {
          px = j;
          py = i;
          field[j][i] = 0;
        } else if (s[j] >= '1' && s[j] <= '9') {
          field[j][i] = s[j] - '0';
        } else if (s[j] == 'X') {
          field[j][i] = -1;
        } else {
          field[j][i] = 0;
        }
      }
    }
    for (int i = 0; i < n; i++) {
      queue<pair<int, int>> play;
      play.push(make_pair(px, py));
      for (int j = 0; j < h; j++) {
        for (int k = 0; k < w; k++) {
          ch[k][j] = 0;
        }
      }
      ch[px][py] = 1;
      for (;;) {
        int x = play.front().first;
        int y = play.front().second;
        if (field[x][y] == i + 1) {
          ans += ch[x][y] - 1;
          px = x;
          py = y;
          break;
        }
        if (x > 0) {
          if (field[x - 1][y] != -1) {
            if (ch[x - 1][y] == 0) {
              play.push(make_pair(x - 1, y));
              ch[x - 1][y] = ch[x][y] + 1;
            }
          }
        }
        if (y > 0) {
          if (field[x][y - 1] != -1) {
            if (ch[x][y - 1] == 0) {
              play.push(make_pair(x, y - 1));
              ch[x][y - 1] = ch[x][y] + 1;
            }
          }
        }
        if (x < w - 1) {
          if (field[x + 1][y] != -1) {
            if (ch[x + 1][y] == 0) {
              play.push(make_pair(x + 1, y));
              ch[x + 1][y] = ch[x][y] + 1;
            }
          }
        }
        if (y < h - 1) {
          if (field[x][y + 1] != -1) {
            if (ch[x][y + 1] == 0) {
              play.push(make_pair(x, y + 1));
              ch[x][y + 1] = ch[x][y] + 1;
            }
          }
        }
        play.pop();
      }
    }
    cout << ans << endl;
  }
  return 0;
}


#include <cstdio>
#include <cstring>

char map[1000][1000];
int h, w, res;

void dfs(int x, int y, char c) {
  if (x < 0 || y < 0 || x >= w || y >= h)
    return;
  if (map[y][x] == c) {
    map[y][x] = '.';
    dfs(x - 1, y, c);
    dfs(x, y - 1, c);
    dfs(x + 1, y, c);
    dfs(x, y + 1, c);
  }
}

int main(void) {
  while (true) {
    res = 0;
    memset(map, 0, sizeof(map));

    scanf("%d%d", &h, &w);
    if (!h && !w)
      break;
    for (int i = 0; i < h; i++)
      scanf("%s", map[i]);

    for (int i = 0; i < h; i++)
      for (int j = 0; j < w; j++)
        if (map[i][j] != '.') {
          res++;
          dfs(j, i, map[i][j]);
        }
    printf("%d\\n", res);
  }
  return 0;
}

#include <cstdio>
#include <queue>
#include <utility>

struct P {
  int x, y;
};

using namespace std;

char map[1005][1005];
int h, w, n;

int distance(char start, char goal) {
  bool visited[1005][1005];
  for (int i = 0; i < h; i++)
    for (int j = 0; j < w; j++)
      visited[i][j] = false;

  queue<pair<P, int>> q;
  for (int i = 0; i < h; i++)
    for (int j = 0; j < w; j++)
      if (map[i][j] == start)
        q.push(pair<P, int>({j, i}, 0));

  while (!q.empty()) {
    pair<P, int> t = q.front();
    q.pop();
    struct P p = t.first;
    int d = t.second;

    if (p.x < 0 || p.y < 0 || p.x >= w || p.y >= h)
      continue;
    if (map[p.y][p.x] == 'X')
      continue;
    if (visited[p.y][p.x])
      continue;
    if (map[p.y][p.x] == goal)
      return d;
    visited[p.y][p.x] = true;

    q.push(pair<P, int>({p.x + 1, p.y}, d + 1));
    q.push(pair<P, int>({p.x, p.y + 1}, d + 1));
    q.push(pair<P, int>({p.x - 1, p.y}, d + 1));
    q.push(pair<P, int>({p.x, p.y - 1}, d + 1));
  }
  return -1;
}

int main(void) {
  int res = 0;

  scanf("%d%d%d", &h, &w, &n);
  for (int i = 0; i < h; i++)
    scanf("%s", map[i]);
  res += distance('S', '1');
  for (int i = 1; i < n; i++)
    res += distance('0' + i, '1' + i);

  printf("%d\\n", res);

  return 0;
}


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

using namespace std;

#define ALL(co) co.begin(), co.end()
#define tpl(...) make_tuple(__VA_ARGS__)

typedef long long LL;
typedef pair<int, int> P;
typedef pair<int, P> IP;
typedef pair<P, P> PP;
typedef vector<int> Array;
typedef vector<vector<int>> Array2;
typedef vector<LL> LArray;
typedef vector<P> PArray;
typedef vector<string> SArray;

const int INF = 1 << 29;
const LL LINF = 1LL << 60;

inline int getInt() {
  int itiv;
  return (cin >> itiv, itiv);
}
template <typename T> void readAll(vector<T> &vec) {
  for (int i = 0, size = vec.size(); i < size; i++)
    cin >> vec[i];
}
template <typename T, typename U> void readAll(vector<pair<T, U>> &vec) {
  for (int i = 0, size = vec.size(); i < size; i++)
    cin >> vec[i].first >> vec[i].second;
}
template <typename T> inline string toString(const T &a) {
  ostringstream oss;
  oss << a;
  return oss.str();
};
inline bool between(int min, int max, int n) { return min <= n && n <= max; }
inline bool inRange(int begin, int end, int n) { return begin <= n && n < end; }
inline bool inRange(int size, int n) { return 0 <= n && n < size; }

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

int main(void) {
  ios::sync_with_stdio(false);
  int h, w, n;
  while (cin >> h >> w >> n && n) {
    SArray stage(h);
    PArray cheese(n + 1);
    for (int i = 0; i < h; i++) {
      cin >> stage[i];
      for (int j = 0; j < w; j++) {
        char c = stage[i][j];
        if (c == 'S') {
          cheese[0] = P(i, j);
        }
        if (inRange(10, c - '0')) {
          cheese[c - '0'] = P(i, j);
        }
      }
    }

    int ans = 0;
    vector<vector<bool>> visited(h, vector<bool>(w));
    for (int i = 0; i < n; i++) {
      P start = cheese[i];
      P goal = cheese[i + 1];

      for (int i = 0; i < h; i++) {
        for (int j = 0; j < w; j++) {
          visited[i][j] = false;
        }
      }
      queue<IP> que;
      que.push(IP(0, start));
      while (!que.empty()) {
        IP ip = que.front();
        que.pop();
        P p = ip.second;
        visited[p.first][p.second] = true;

        if (p == goal) {
          ans += ip.first;
          break;
        }

        for (int j = 0; j < 4; j++) {
          int nr = p.first + dr[j], nc = p.second + dc[j];
          if (!inRange(h, nr) || !inRange(w, nc) || stage[nr][nc] == 'X' ||
              visited[nr][nc])
            continue;
          visited[p.first][p.second] = true;
          que.push(IP(ip.first + 1, P(nr, nc)));
        }
      }
    }

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

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

using namespace std;

#define ALL(co) co.begin(), co.end()
#define tpl(...) make_tuple(__VA_ARGS__)

typedef long long LL;
typedef pair<int, int> P;
typedef pair<int, P> IP;
typedef pair<P, P> PP;
typedef vector<int> Array;
typedef vector<vector<int>> Array2;
typedef vector<LL> LArray;
typedef vector<P> PArray;
typedef vector<string> SArray;

const int INF = 1 << 29;
const LL LINF = 1LL << 60;

inline int getInt() {
  int itiv;
  return (cin >> itiv, itiv);
}
template <typename T> void readAll(vector<T> &vec) {
  for (int i = 0, size = vec.size(); i < size; i++)
    cin >> vec[i];
}
template <typename T, typename U> void readAll(vector<pair<T, U>> &vec) {
  for (int i = 0, size = vec.size(); i < size; i++)
    cin >> vec[i].first >> vec[i].second;
}
template <typename T> inline string toString(const T &a) {
  ostringstream oss;
  oss << a;
  return oss.str();
};
inline bool between(int min, int max, int n) { return min <= n && n <= max; }
inline bool inRange(int begin, int end, int n) { return begin <= n && n < end; }
inline bool inRange(int size, int n) { return 0 <= n && n < size; }

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

int main(void) {
  ios::sync_with_stdio(false);
  int h, w, n;
  while (cin >> h >> w >> n && n) {
    SArray stage(h);
    PArray cheese(n + 1);
    for (int i = 0; i < h; i++) {
      cin >> stage[i];
      for (int j = 0; j < w; j++) {
        char c = stage[i][j];
        if (c == 'S') {
          cheese[0] = P(i, j);
        }
        if (inRange(10, c - '0')) {
          cheese[c - '0'] = P(i, j);
        }
      }
    }

    int ans = 0;
    vector<vector<bool>> visited(h, vector<bool>(w));
    for (int i = 0; i < n; i++) {
      P start = cheese[i];
      P goal = cheese[i + 1];

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

      queue<IP> que;
      que.push(IP(0, start));
      while (!que.empty()) {
        IP ip = que.front();
        que.pop();
        P p = ip.second;
        visited[p.first][p.second] = true;

        if (p == goal) {
          ans += ip.first;
          break;
        }

        for (int j = 0; j < 4; j++) {
          int nr = p.first + dr[j], nc = p.second + dc[j];
          if (!inRange(h, nr) || !inRange(w, nc) || stage[nr][nc] == 'X' ||
              visited[nr][nc])
            continue;
          visited[nr][nc] = true;
          que.push(IP(ip.first + 1, P(nr, nc)));
        }
      }
    }

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


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

using namespace std;

#define ALL(co) co.begin(), co.end()
#define tpl(...) make_tuple(__VA_ARGS__)

typedef long long LL;
typedef pair<int, int> P;
typedef pair<P, int> PI;
typedef pair<P, P> PP;
typedef vector<int> Array;
typedef vector<vector<int>> Array2;
typedef vector<LL> LArray;
typedef vector<P> PArray;
typedef vector<string> SArray;

const int INF = 1 << 29;
const LL LINF = 1LL << 60;

inline int getInt() {
  int itiv;
  return (cin >> itiv, itiv);
}
template <typename T> void readAll(vector<T> &vec) {
  for (int i = 0, size = vec.size(); i < size; i++)
    cin >> vec[i];
}
template <typename T, typename U> void readAll(vector<pair<T, U>> &vec) {
  for (int i = 0, size = vec.size(); i < size; i++)
    cin >> vec[i].first >> vec[i].second;
}
template <typename T> inline string toString(const T &a) {
  ostringstream oss;
  oss << a;
  return oss.str();
};
inline bool between(int min, int max, int n) { return min <= n && n <= max; }
inline bool inRange(int begin, int end, int n) { return begin <= n && n < end; }
inline bool inRange(int size, int n) { return 0 <= n && n < size; }

int dx[] = {-1, 0, 1, 0}, dy[] = {0, -1, 0, 1};
int dr[] = {0, -1, 0, 1}, dc[] = {-1, 0, 1, 0};
bool visited[1000][1000];
char stage[1000][1000];
int h, w, n;

int main(void) {
  ios::sync_with_stdio(false);
  while (cin >> h >> w >> n && n) {
    PArray goals(n + 1);
    for (int i = 0; i < h; i++) {
      for (int j = 0; j < w; j++) {
        cin >> stage[i][j];
        if (stage[i][j] == 'S')
          goals[0] = P(i, j);
        int num = stage[i][j] - '0';
        if (inRange(n + 1, num))
          goals[num] = P(i, j);
      }
    }

    int ans = 0;
    for (int i = 0; i < n; i++) {
      P start = goals[i], goal = goals[i + 1];
      memset(visited, false, sizeof(visited));
      queue<PI> que;
      que.push(PI(start, 0));
      while (!que.empty()) {
        PI pi = que.front();
        que.pop();
        if (goal == pi.first) {
          ans += pi.second;
          break;
        }
        int r = pi.first.first, c = pi.first.second;

        for (int i = 0; i < 4; i++) {
          int nr = r + dr[i], nc = c + dc[i];
          if (!inRange(h, nr) || !inRange(w, nc) || stage[nr][nc] == 'X' ||
              visited[nr][nc])
            continue;
          que.push(PI(P(nr, nc), pi.second + 1));
          visited[r][c] = true;
        }
      }
    }
    cout << ans << endl;
  }
  return 0;
}

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

using namespace std;

#define ALL(co) co.begin(), co.end()
#define tpl(...) make_tuple(__VA_ARGS__)

typedef long long LL;
typedef pair<int, int> P;
typedef pair<P, int> PI;
typedef pair<P, P> PP;
typedef vector<int> Array;
typedef vector<vector<int>> Array2;
typedef vector<LL> LArray;
typedef vector<P> PArray;
typedef vector<string> SArray;

const int INF = 1 << 29;
const LL LINF = 1LL << 60;

inline int getInt() {
  int itiv;
  return (cin >> itiv, itiv);
}
template <typename T> void readAll(vector<T> &vec) {
  for (int i = 0, size = vec.size(); i < size; i++)
    cin >> vec[i];
}
template <typename T, typename U> void readAll(vector<pair<T, U>> &vec) {
  for (int i = 0, size = vec.size(); i < size; i++)
    cin >> vec[i].first >> vec[i].second;
}
template <typename T> inline string toString(const T &a) {
  ostringstream oss;
  oss << a;
  return oss.str();
};
inline bool between(int min, int max, int n) { return min <= n && n <= max; }
inline bool inRange(int begin, int end, int n) { return begin <= n && n < end; }
inline bool inRange(int size, int n) { return 0 <= n && n < size; }

int dx[] = {-1, 0, 1, 0}, dy[] = {0, -1, 0, 1};
int dr[] = {0, -1, 0, 1}, dc[] = {-1, 0, 1, 0};
bool visited[1000][1000];
char stage[1000][1000];
int h, w, n;

int main(void) {
  ios::sync_with_stdio(false);
  while (cin >> h >> w >> n && n) {
    PArray goals(n + 1);
    for (int i = 0; i < h; i++) {
      for (int j = 0; j < w; j++) {
        cin >> stage[i][j];
        if (stage[i][j] == 'S')
          goals[0] = P(i, j);
        int num = stage[i][j] - '0';
        if (inRange(n + 1, num))
          goals[num] = P(i, j);
      }
    }

    int ans = 0;
    for (int i = 0; i < n; i++) {
      P start = goals[i], goal = goals[i + 1];
      memset(visited, false, sizeof(visited));
      queue<PI> que;
      que.push(PI(start, 0));
      while (!que.empty()) {
        PI pi = que.front();
        que.pop();
        if (goal == pi.first) {
          ans += pi.second;
          break;
        }
        int r = pi.first.first, c = pi.first.second;

        for (int i = 0; i < 4; i++) {
          int nr = r + dr[i], nc = c + dc[i];
          if (!inRange(h, nr) || !inRange(w, nc) || stage[nr][nc] == 'X' ||
              visited[nr][nc])
            continue;
          que.push(PI(P(nr, nc), pi.second + 1));
          visited[nr][nc] = true;
        }
      }
    }
    cout << ans << endl;
  }
  return 0;
}


#include <iostream>
#include <queue>
#include <string.h>
using namespace std;
long long cheese[1001][1001];
long long check[1001][1001];
char num[11] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
int q[4] = {0, 1, 0, -1};
int p[4] = {1, 0, -1, 0};
struct ST {
  int a;
  int b;
  int c;
  int d;
};
int main() {
  memset(cheese, 0, sizeof(cheese));
  memset(check, 0, sizeof(check));
  int h, w, n;
  int i, j, m;
  int ys, xs;
  char data;
  queue<ST> Q;
  ST x;
  ST y;
  cin >> h >> w >> n; //??¢??????????????°
  for (i = 1; i <= h; i++) {
    for (j = 1; j <= w; j++) {
      cin >> data;
      if (data == 'S') { //????????????
        ys = i;          //??????????????§?¨?
        xs = j;
      } else if (data == 'X') { //?????????
        cheese[i][j] = -1;
      } else if (data != '.') {
        for (m = 1; m <= 9; m++) {
          if (num[m] == data) {
            cheese[i][j] = m;
          }
        }
      }
    }
  }
  x.a = ys;
  x.b = xs;
  x.c = 0;
  x.d = 1;
  Q.push(x);
  while (!Q.empty()) {
    y = Q.front();
    Q.pop();
    if (check[y.a][y.b] == 1)
      continue;
    check[y.a][y.b] = 1;
    if (y.d == cheese[y.a][y.b]) {
      if (n == y.d)
        break;
      memset(check, 0, sizeof(check));
      while (!Q.empty()) {
        Q.pop();
      }
      y.d += 1;
      x.a = y.a;
      x.b = y.b;
      x.c = y.c;
      x.d = y.d;
      Q.push(x);
      continue;
    }
    for (i = 0; i < 4; i++) {
      if (y.a + q[i] > 0 && y.a + q[i] <= h && y.b + p[i] > 0 &&
          y.b + p[i] <= w && check[y.a + q[i]][y.b + p[i]] != 1 &&
          cheese[y.a][y.b] != -1) {
        x.a = y.a + q[i];
        x.b = y.b + p[i];
        x.c = y.c + 1;
        x.d = y.d;
        Q.push(x);
      }
    }
  }
  cout << y.c << endl;
  return 0;
}


#include <cstdio>
#include <iostream>
#include <queue>
#define REP(i, n) for (int i = 0; i < (n); i++)
#define FOR(i, a, b) for (int i = (a); i < (b); i++)

using namespace std;

struct P {
  int x;
  int y;
};

int w, h, n;
const int INF = 1e+8;
char feld[1010][1010];
int d[1010][1010];
int sx, sy, gx, gy;
int dx[4] = {0, 0, 1, -1};
int dy[4] = {1, -1, 0, 0};
int ans = 0;
P che[15];

int bfs() {
  for (int i = 0; i < n; i++) {
    P sp = che[i];
    sx = che[i].x;
    sy = che[i].y;
    gx = che[i + 1].x;
    gy = che[i + 1].y;
    queue<P> que;
    for (int y = 0; y < h; y++)
      for (int x = 0; x < w; x++)
        d[y][x] = INF;
    que.push(sp);
    d[sy][sx] = 0;
    while (!que.empty()) {
      P p = que.front();
      que.pop();
      int x = p.x;
      int y = p.y;
      if (x == gx && y == gy) {
        ans += d[gy][gx];
        break;
      }
      for (int i = 0; i < 4; i++) {
        int nx = x + dx[i];
        int ny = y + dy[i];
        if (nx < 0 || ny < 0 && nx >= w && ny >= h)
          continue;
        if (feld[ny][nx] != 'X' && d[ny][nx] == INF) {
          P next;
          next.x = nx;
          next.y = ny;
          que.push(next);
          d[ny][nx] = d[y][x] + 1;
        }
      }
    }
  }
  return 0;
}

int main() {
  cin >> h >> w >> n;
  for (int y = 0; y < h; y++) {
    for (int x = 0; x < w; x++) {
      scanf(" %c", &feld[y][x]);
      if (feld[y][x] == 'S') {
        che[0].x = x;
        che[0].y = y;
      } else if (feld[y][x] >= '1' && feld[y][x] <= '9') {
        char c = feld[y][x];
        che[c - '0'].x = x;
        che[c - '0'].y = y;
      }
    }
  }
  bfs();
  cout << ans << endl;
  return 0;
}

#include <cstdio>
#include <iostream>
#include <queue>
#define REP(i, n) for (int i = 0; i < (n); i++)
#define FOR(i, a, b) for (int i = (a); i < (b); i++)

using namespace std;

struct P {
  int x;
  int y;
};

int w, h, n;
const int INF = 1e+8;
char feld[1010][1010];
int d[1010][1010];
int sx, sy, gx, gy;
int dx[4] = {0, 0, 1, -1};
int dy[4] = {1, -1, 0, 0};
int ans;
P che[15];

void bfs() {
  REP(i, n) {
    P sp = che[i];
    sx = che[i].x;
    sy = che[i].y;
    gx = che[i + 1].x;
    gy = che[i + 1].y;
    REP(y, h) REP(x, w) d[y][x] = INF;
    queue<P> que;
    que.push(sp);
    d[sy][sx] = 0;
    while (!que.empty()) {
      P p = que.front();
      que.pop();
      int x = p.x;
      int y = p.y;
      if (x == gx && y == gy) {
        ans += d[gy][gx];
        break;
      }
      REP(i, 4) {
        int nx = x + dx[i];
        int ny = y + dy[i];
        if (nx < 0 || nx >= w || ny < 0 || ny >= h)
          continue;
        if (feld[ny][nx] != 'X' && d[ny][nx] == INF) {
          P next;
          next.x = nx;
          next.y = ny;
          que.push(next);
          d[ny][nx] = d[y][x] + 1;
        }
      }
    }
  }
}

int main() {
  cin >> h >> w >> n;
  REP(y, h) {
    REP(x, w) {
      scanf(" %c", &feld[y][x]);
      if (feld[y][x] == 'S') {
        che[0].x = x;
        che[0].y = y;
      } else if (feld[y][x] >= '1' && feld[y][x] <= '9') {
        char c = feld[y][x];
        che[c - '0'].x = x;
        che[c - '0'].y = y;
      }
    }
  }
  bfs();
  cout << ans << endl;
  return 0;
}


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

using namespace std;

#define REP(i, n) for (int i = 0; i < (n); i++)
#define FOR(i, a, b) for (int i = (a); i < (b); i++)
#define INF 1e+7

struct P {
  int x;
  int y;
};

int w, h, n;
char feld[1010][1010];
int d[1010][1010];
int sx, sy, gx, gy;
int dx[4] = {0, 0, 1, -1};
int dy[4] = {1, -1, 0, 0};
int ans = 0;
P che[15];

int bfs() {
  REP(i, n) {
    P sp = che[i];
    sx = che[i].x;
    sy = che[i].y;
    gx = che[i + 1].x;
    gy = che[i + 1].y;
    queue<P> que;
    REP(y, h) REP(x, w) d[y][x] = INF;
    que.push(sp);
    d[sy][sx] = 0;
    while (!que.empty()) {
      P p = que.front();
      que.pop();
      int x = p.x;
      int y = p.y;
      if (x == gx && y == gy) {
        ans += d[gy][gx];
        break;
      }
      REP(i, 4) {
        int nx = x + dx[i];
        int ny = y + dy[i];
        if (nx < 0 || ny < 0 && nx >= w && ny >= h)
          continue;
        if (feld[ny][nx] != 'X' && d[ny][nx] == INF) {
          P next;
          next.x = nx;
          next.y = ny;
          que.push(next);
          d[ny][nx] = d[y][x] + 1;
        }
      }
    }
  }
  return 0;
}

int main() {
  cin >> h >> w >> n;
  REP(y, h) {
    REP(x, w) {
      scanf(" %c", &feld[y][x]);
      if (feld[y][x] == 'S') {
        che[0].x = x;
        che[0].y = y;
      } else if (feld[y][x] >= '1' && feld[y][x] <= '9') {
        char c = feld[y][x];
        che[c - '0'].x = x;
        che[c - '0'].y = y;
      }
    }
  }
  bfs();
  cout << ans << endl;
  return 0;
}

#include <cstdio>
#include <iostream>
#include <map>
#include <queue>
#include <string>

using namespace std;

typedef struct P {
  int x;
  int y;
} P;

int h, w, n;

const int INF = 100000000;

char feld[1010][1010];
P ch[15];
int d[1010][1010];
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
int sx, sy;
int gx, gy;
int ans = 0;

int bfs() {
  for (int i = 0; i < n; i++) {
    P s_xy = ch[i];
    sx = ch[i].x;
    sy = ch[i].y;
    gx = ch[i + 1].x;
    gy = ch[i + 1].y;
    for (int y = 0; y < h; y++)
      for (int x = 0; x < w; x++)
        d[y][x] = INF;
    queue<P> que;
    que.push(s_xy);
    d[sy][sx] = 0;
    while (!que.empty()) {
      P p = que.front();
      que.pop();
      int x = p.x;
      int y = p.y;
      if (x == gx && y == gy) {
        ans += d[gy][gx];
        break;
      }
      for (int i = 0; i < 4; i++) {
        int nx = x + dx[i];
        int ny = y + dy[i];
        if (nx < 0 || nx >= w || ny < 0 || ny >= h)
          continue;
        if (feld[ny][nx] != 'X' && d[ny][nx] == INF) {
          P n;
          n.x = nx;
          n.y = ny;
          d[ny][nx] = d[y][x] + 1;
          que.push(n);
        }
      }
    }
  }
  return 0;
}

int main() {
  cin >> h >> w >> n;
  char c;
  for (int y = 0; y < h; y++) {
    for (int x = 0; x < w; x++) {
      scanf(" %c", &feld[y][x]);
      c = feld[y][x];
      if (feld[y][x] == 'S') {
        ch[0].x = x;
        ch[0].y = y;
      }
      if (c >= '1' && c <= '9') {
        ch[c - '0'].x = x;
        ch[c - '0'].y = y;
      }
    }
  }
  bfs();
  cout << ans << endl;
  return 0;
}


#include <cstdio>
#include <iostream>
#include <queue>
#include <string.h>

using namespace std;

int W, H, N;
typedef pair<int, int> P;
queue<P> que;
char maze[1003][1003];
int d[1003][1003];
int pos_x, pos_y;
int sh_x[4] = {0, 0, -1, 1};
int sh_y[4] = {1, -1, 0, 0};
int res = 0;
int strength = 1;

void clear(queue<P> &q) {
  queue<P> empty;
  swap(q, empty);
}

void solve() {
  que.push(P(pos_x, pos_y));
  memset(d, -1, sizeof(d));
  d[pos_y][pos_x] = 0;

  while (que.size()) {
    P pos = que.front();
    que.pop();
    if (maze[pos.second][pos.first] - '0' == strength) {
      // printf("[%d] [%d] %d\\n", pos.second, pos.first, res);
      clear(que);
      res += d[pos.second][pos.first];

      strength++;
      if (strength == N + 1) {
        break;
      }

      // for (int i=0;i<H;i++) {
      //   for (int j=0;j<W;j++) {
      //     if (maze[i][j] == '#') maze[i][j] = '.';
      //   }
      // }
      memset(d, -1, sizeof(d));
      d[pos.second][pos.first] = 0;

      // while(que.size()) que.pop();
      // maze[pos.second][pos.first] = '#';
      que.push(pos);
      continue;
    }
    for (int i = 0; i < 4; i++) {
      int new_x = pos.first + sh_x[i];
      int new_y = pos.second + sh_y[i];
      if (new_x >= 0 && new_x < W && new_y >= 0 && new_y < H &&
          maze[new_y][new_x] != 'X' && d[new_y][new_x] == -1) {
        // printf("Go to [%d] [%d]\\n", new_y, new_x);
        que.push(P(new_x, new_y));
        // if (maze[new_y][new_x] == '.') {
        //   maze[new_y][new_x] = '#';
        // }
        d[new_y][new_x] = d[pos.second][pos.first] + 1;
      }
    }
  }
}

int main() {
  while (1) {
    scanf("%d %d %d", &H, &W, &N);
    getchar();
    if (!W && !H) {
      break;
    }

    for (int i = 0; i < H; i++) {
      fgets(maze[i], 1002, stdin);
    }

    for (int i = 0; i < H; i++) {
      for (int j = 0; j < W; j++) {
        if (maze[i][j] == 'S') {
          pos_x = j;
          pos_y = i;
        }
      }
    }

    solve();
    printf("%d\\n", res);
    strength = 1;
    res = 0;
  }
  return 0;
}

#include <cstdio>
#include <iostream>
#include <queue>
#include <string.h>

using namespace std;

int W, H, N;
typedef pair<int, int> P;
queue<P> que;
char maze[1003][1003];
int timer[1003][1003];
int pos_x, pos_y;
int sh_x[4] = {0, 0, -1, 1};
int sh_y[4] = {1, -1, 0, 0};
int res = 0;
int strength = 1;

void solve() {
  que.push(P(pos_x, pos_y));

  while (que.size()) {
    P pos = que.front();
    que.pop();
    if (maze[pos.second][pos.first] - '0' == strength) {
      // printf("[%d] [%d]\\n", pos.second, pos.first);
      while (que.size())
        que.pop();
      strength++;
      if (strength == N + 1) {
        res = timer[pos.second][pos.first];
        break;
      }

      for (int i = 0; i < H; i++) {
        for (int j = 0; j < W; j++) {
          if (maze[i][j] == '#')
            maze[i][j] = '.';
        }
      }

      maze[pos.second][pos.first] = '#';
      que.push(pos);
      continue;
    }
    for (int i = 0; i < 4; i++) {
      int new_x = pos.first + sh_x[i];
      int new_y = pos.second + sh_y[i];
      if (new_x >= 0 && new_x < W && new_y >= 0 && new_y < H &&
          maze[new_y][new_x] != '#' && maze[new_y][new_x] != 'X') {
        // printf("Go to [%d] [%d]\\n", new_y, new_x);
        que.push(P(new_x, new_y));
        if (maze[new_y][new_x] == '.') {
          maze[new_y][new_x] = '#';
        }
        timer[new_y][new_x] = timer[pos.second][pos.first] + 1;
      }
    }
  }
}

int main() {
  scanf("%d %d %d", &H, &W, &N);
  getchar();

  for (int i = 0; i < H; i++) {
    fgets(maze[i], 1002, stdin);
    maze[i][W] = '#';
  }

  for (int i = 0; i < H; i++) {
    for (int j = 0; j < W; j++) {
      if (maze[i][j] == 'S') {
        pos_x = j;
        pos_y = i;
      }
      if (i == H - 1) {
        maze[H][j] = '#';
      }
    }
  }

  solve();
  printf("%d\\n", res);
  return 0;
}


#include <iostream>
#include <queue>
#include <utility>
#define INF 5000000
using namespace std;

char fl[1010][1010];

int bfs(int sx, int sy, int gx, int gy, int mx, int my) {
  typedef pair<int, int> P;
  int d[1010][1010];
  int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};

  for (int i = 0; i < mx; i++)
    for (int j = 0; j < my; j++)
      d[i][j] = INF;

  queue<P> que;
  que.push(P(sx, sy));
  d[sx][sy] = 0;

  while (que.size()) {
    P p = que.front();
    que.pop();

    if (p.first == gx && p.second == gy)
      break;

    for (int i = 0; i < 4; i++) {
      int nx = p.first + dx[i], ny = p.second + dy[i];

      if (0 <= nx && nx < my && 0 <= ny && ny < mx && fl[nx][ny] != 'X' &&
          d[nx][ny] != INF) {
        que.push(P(nx, ny));
        d[nx][ny] = d[p.first][p.second] + 1;
      }
    }
  }
  return d[gx][gy];
}

int main() {
  int h, w, n;
  cin >> h >> w >> n;
  int al = 0;
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      cin >> fl[i][j];
    }
  }
  char a[10] = {'S', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
  for (int i = 0; i < n; i++) {
    int sx, sy;
    int gx, gy;
    for (int j = 0; j < h; j++) {
      for (int k = 0; k < w; k++) {

        if (fl[j][k] == a[i]) {
          sx = j;
          sy = k;
        }
        if (fl[j][k] == a[i + 1]) {
          gx = j;
          gy = k;
        }
      }
    }

    al += bfs(sx, sy, gx, gy, h, w);
  }
  cout << al << endl;
  return 0;
}

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

const int INF = 2000000;
char fl[1010][1010];
int d[1010][1010];

int bfs(int sx, int sy, int gx, int gy, int mx, int my) {
  typedef pair<int, int> P;
  int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};

  for (int i = 0; i < mx; i++)
    for (int j = 0; j < my; j++)
      d[i][j] = INF;

  queue<P> que;
  que.push(P(sx, sy));
  d[sx][sy] = 0;

  while (que.size()) {
    P p = que.front();
    que.pop();

    if (p.first == gx && p.second == gy)
      break;

    for (int i = 0; i < 4; i++) {
      int nx = p.first + dx[i], ny = p.second + dy[i];

      if (0 <= nx && nx < mx && 0 <= ny && ny < my && fl[nx][ny] != 'X' &&
          d[nx][ny] == INF) {
        que.push(P(nx, ny));
        d[nx][ny] = d[p.first][p.second] + 1;
      }
    }
  }
  return d[gx][gy];
}

int main() {
  int h, w, n;
  cin >> h >> w >> n;
  int al = 0;
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      cin >> fl[i][j];
    }
  }
  char a[10] = {'S', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
  for (int i = 0; i < n; i++) {
    int sx, sy;
    int gx, gy;
    for (int j = 0; j < h; j++) {
      for (int k = 0; k < w; k++) {

        if (fl[j][k] == a[i]) {
          sx = j;
          sy = k;
        }
        if (fl[j][k] == a[i + 1]) {
          gx = j;
          gy = k;
        }
      }
    }

    al += bfs(sx, sy, gx, gy, h, w);
  }

  cout << al << endl;
  getchar();
  getchar();
  return 0;
}


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

#define fi first
#define se second
#define x second
#define y first

typedef pair<int, int> pii;

vector<string> in;
int H, W, N;

int search_length(char s, char g) {
  queue<pair<pii, int>> que;
  int vx[] = {1, -1, 0, 0};
  int vy[] = {0, 0, 1, -1};
  for (int i = 0; i < in.size(); i++) {
    for (int j = 0; j < in[i].size(); j++) {
      if (in[i][j] == s) {
        que.push(pair<pii, int>(pii(i, j), 0));
        j = in[i].size();
        i = in.size();
      }
    }
  }
  int visited[1024][1024] = {0};
  while (!que.empty()) {
    pair<pair<int, int>, int> tmp;
    tmp = que.front();
    que.pop();
    for (int i = 0; i < 4; i++) {
      int x_, y_;
      x_ = tmp.fi.x + vx[i];
      y_ = tmp.fi.y + vy[i];
      if (!(x_ < 0 || (int)in[0].size() <= x_ || y_ < 0 ||
            (int)in.size() <= y_)) {
        if (in[y_][x_] == g) {
          return tmp.se + 1;
        }
        if (!visited[y_][x_] && in[y_][x_] != 'X') {
          visited[y_][x_] = 1;
          que.push(pair<pii, int>(pii(y_, x_), tmp.se + 1));
        }
      }
    }
  }
  cout << "reach" << endl;
  return -1;
}

int main() {
  cin >> H >> W >> N;
  int ret = 0;
  for (int i = 0; i < H; i++) {
    string tmp;
    cin >> tmp;
    in.push_back(tmp);
  }

  for (int i = 0; i < N; i++) {
    char s, g;
    s = i + '0';
    g = i + 1 + '0';
    if (i == 0)
      s = 'S';
    ret += search_length(s, g);
  }
  cout << ret << endl;
  return 0;
}

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

#define fi first
#define se second
#define x second
#define y first

typedef pair<int, int> pii;

vector<string> in;
int H, W, N;

int visited[1024][1024] = {0};

int search_length(char s, char g) {
  fill(visited[0], visited[0] + 1024 * 1024, 0);
  queue<pair<pii, int>> que;
  int vx[] = {1, -1, 0, 0};
  int vy[] = {0, 0, 1, -1};
  for (int i = 0; i < in.size(); i++) {
    for (int j = 0; j < in[0].size(); j++) {
      if (in[i][j] == s) {
        que.push(pair<pii, int>(pii(i, j), 0));
        j = in[i].size();
        i = in.size();
      }
    }
  }
  while (!que.empty()) {
    pair<pair<int, int>, int> tmp;
    tmp = que.front();
    que.pop();
    for (int i = 0; i < 4; i++) {
      int x_, y_;
      x_ = tmp.fi.x + vx[i];
      y_ = tmp.fi.y + vy[i];
      if (!(x_ < 0 || (int)in[0].size() <= x_ || y_ < 0 ||
            (int)in.size() <= y_)) {
        if (in[y_][x_] == g) {
          return tmp.se + 1;
        }
        if (!visited[y_][x_] && in[y_][x_] != 'X') {
          visited[y_][x_] = 1;
          que.push(pair<pii, int>(pii(y_, x_), tmp.se + 1));
        }
      }
    }
  }
  return -1;
}

int main() {
  cin >> H >> W >> N;
  int ret = 0;
  for (int i = 0; i < H; i++) {
    string tmp;
    cin >> tmp;
    in.push_back(tmp);
  }

  for (int i = 0; i < N; i++) {
    char s, g;
    s = i + '0';
    g = i + 1 + '0';
    if (i == 0)
      s = 'S';
    ret += search_length(s, g);
  }
  cout << ret << endl;
  return 0;
}


#include <algorithm>
#include <cmath>
#include <iostream>
#include <queue>
#include <vector>
#define debug(ARGS) cout << #ARGS << ": " << ARGS << endl;
#define ll long long

#define INF (int)1e7
#define p pair<int, int>
#define F 0
#define X -1
#define S -2

using namespace std;

int convert(char c) {
  int ret;

  if ('1' <= c && c <= '9')
    ret = c - '1' + 1;
  else if (c == '.')
    ret = F;
  else if (c == 'X')
    ret = X;
  else if (c == 'S')
    ret = S;
  else
    ret = -3;

  return ret;
}

p find_nest(vector<vector<int>> &v, int num) {
  int h = v.size(), w = v[0].size();
  p ret;

  for (int i = 0; i < h; i++)
    for (int j = 0; j < w; j++)
      if (v[i][j] == num)
        ret = p(i, j);

  return ret;
}

int count_minite(vector<vector<int>> &v, int start, int end) {
  int h = v.size(), w = v[0].size();
  int ret = -1;
  vector<vector<bool>> m;
  m.resize(h);
  for (int i = 0; i < h; i++)
    m[i].resize(w, false);
  queue<pair<p, int>> q;
  q.push(pair<p, int>(find_nest(v, start), 0));

  while (!q.empty()) {
    p here = q.front().first;
    ret = q.front().second;
    q.pop();
    int y = here.first, x = here.second;

    if (v[y][x] == end)
      break;
    else if (v[y][x] == X)
      continue;

    m[y][x] = true;

    if (x > 0 && !m[y][x - 1])
      q.push(pair<p, int>(p(y, x - 1), ret + 1));
    if (x < w - 1 && !m[y][x + 1])
      q.push(pair<p, int>(p(y, x + 1), ret + 1));
    if (y > 0 && !m[y - 1][x])
      q.push(pair<p, int>(p(y - 1, x), ret + 1));
    if (y < h - 1 && !m[y + 1][x])
      q.push(pair<p, int>(p(y + 1, x), ret + 1));
  }

  return ret;
}

int main() {
  int h, w, n;
  cin >> h;
  cin >> w;
  cin >> n;
  vector<vector<int>> v;
  v.resize(h);
  for (int i = 0; i < h; i++)
    v[i].resize(w);
  int count = 0;

  for (int i = 0; i < h; i++)
    for (int j = 0; j < w; j++) {
      char c;
      cin >> c;
      v[i][j] = convert(c);
    }

  int start = S;
  for (int i = 1; i <= n; i++) {
    count += count_minite(v, start, i);
    start = i;
  }

  cout << count << endl;

  return 0;
}

#include <algorithm>
#include <cmath>
#include <iostream>
#include <queue>
#include <vector>
#define debug(ARGS) cout << #ARGS << ": " << ARGS << endl;
#define ll long long

#define INF (int)1e7
#define p pair<int, int>
#define F 0
#define X -1
#define S -2

using namespace std;

int convert(char c) {
  int ret;

  if ('1' <= c && c <= '9')
    ret = c - '1' + 1;
  else if (c == '.')
    ret = F;
  else if (c == 'X')
    ret = X;
  else if (c == 'S')
    ret = S;
  else
    ret = -3;

  return ret;
}

p find_nest(vector<vector<int>> &v, int num) {
  int h = v.size(), w = v[0].size();
  p ret;

  for (int i = 0; i < h; i++)
    for (int j = 0; j < w; j++)
      if (v[i][j] == num)
        ret = p(i, j);

  return ret;
}

int count_minite(vector<vector<int>> v, int start, int end) {
  int h = v.size(), w = v[0].size();
  int ret = -1;
  // vector< vector<bool> > m; m.resize(h); for(int i = 0; i < h; i++)
  // m[i].resize(w, false);
  queue<pair<p, int>> q;
  q.push(pair<p, int>(find_nest(v, start), 0));

  while (!q.empty()) {
    p here = q.front().first;
    ret = q.front().second;
    q.pop();
    int y = here.first, x = here.second;

    if (v[y][x] == end)
      break;
    else if (v[y][x] == X)
      continue;

    v[y][x] = X;

    if (x > 0 && v[y][x - 1] != X)
      q.push(pair<p, int>(p(y, x - 1), ret + 1));
    if (x < w - 1 && v[y][x + 1] != X)
      q.push(pair<p, int>(p(y, x + 1), ret + 1));
    if (y > 0 && v[y - 1][x] != X)
      q.push(pair<p, int>(p(y - 1, x), ret + 1));
    if (y < h - 1 && v[y + 1][x] != X)
      q.push(pair<p, int>(p(y + 1, x), ret + 1));
  }

  return ret;
}

int main() {
  int h, w, n;
  cin >> h;
  cin >> w;
  cin >> n;
  vector<vector<int>> v;
  v.resize(h);
  for (int i = 0; i < h; i++)
    v[i].resize(w);
  int count = 0;

  for (int i = 0; i < h; i++)
    for (int j = 0; j < w; j++) {
      char c;
      cin >> c;
      v[i][j] = convert(c);
    }

  int start = S;
  for (int i = 1; i <= n; i++) {
    count += count_minite(v, start, i);
    start = i;
  }

  cout << count << endl;

  return 0;
}


#include <iostream>
#include <queue>

using namespace std;

typedef pair<int, int> p;

int w, h, n, result, steps;
char parent[1000][1000];
bool visited[1000][1000], map[1000][1000];
p start, last_start, goal, cur, cheese[10];
queue<p> myqueue;

void init(int in) {
  start = last_start;

  while (!myqueue.empty())
    myqueue.pop();

  for (int i = 0; i < w; ++i) {
    for (int j = 0; j < h; ++j) {
      parent[i][j] = '0';
      if (map[i][j] == false) {
        visited[i][j] = true;
      } else {
        visited[i][j] = false;
      }
      goal = cheese[in];
    }
  }
  return;
}

int main() {
  cin >> w >> h >> n;

  char input;
  for (int i = 0; i < w; ++i) {
    for (int j = 0; j < h; ++j) {
      cin >> input;
      if (input == 'X')
        map[i][j] = false;
      else
        map[i][j] = true;
      if (input == 'S')
        last_start = make_pair(i, j);
      if (input != 'X' && input != 'S' && input != '.') {
        cheese[input - '0'] = make_pair(i, j);
        // cout << "cheese " << input-'0' << " : " << i << " " << j << endl;
      }
    }
  }

  result = 0;
  for (int i = 1; i <= n; ++i) {
    init(i);
    myqueue.push(start);

    while (!myqueue.empty()) {
      cur = myqueue.front();
      myqueue.pop();

      if (cur == goal) {
        break;
      }

      visited[cur.first][cur.second] = true;

      int x = cur.first, y = cur.second;
      if (x - 1 >= 0 && !visited[x - 1][y]) {
        myqueue.push(make_pair(x - 1, y));
        parent[x - 1][y] = '1';
      }
      if (y - 1 >= 0 && !visited[x][y - 1]) {
        myqueue.push(make_pair(x, y - 1));
        parent[x][y - 1] = '2';
      }
      if (x + 1 < w && !visited[x + 1][y]) {
        myqueue.push(make_pair(x + 1, y));
        parent[x + 1][y] = '3';
      }
      if (y + 1 < h && !visited[x][y + 1]) {
        myqueue.push(make_pair(x, y + 1));
        parent[x][y + 1] = '4';
      }
    }
    int counter = 0;
    p bcur = goal;
    while (bcur != start) {
      counter++;
      if (parent[bcur.first][bcur.second] == '1')
        bcur.first++;
      else if (parent[bcur.first][bcur.second] == '2')
        bcur.second++;
      else if (parent[bcur.first][bcur.second] == '3')
        bcur.first--;
      else if (parent[bcur.first][bcur.second] == '4')
        bcur.second--;
    }
    result += counter;
    // cout << counter << endl;
    last_start = goal;
  }

  cout << result << endl;
  return 0;
}

#include <iostream>
#include <queue>
#define INF 300000

using namespace std;

typedef pair<int, int> p;

int w, h, n, result, steps;
int visited[1000][1000];
bool map[1000][1000];
p start, last_start, goal, cur, cheese[10];
queue<p> myqueue;

void init(int in) {
  start = last_start;

  while (!myqueue.empty())
    myqueue.pop();

  for (int i = 0; i < w; ++i) {
    for (int j = 0; j < h; ++j) {
      if (map[i][j] == false) {
        visited[i][j] = -1;
      } else {
        visited[i][j] = INF;
      }
      goal = cheese[in];
    }
  }
  /*for(int i=0; i<w; ++i){
      for(int j=0; j<h; ++j){

          cout << visited[i][j] << " ";

      }
      cout << endl;
  }*/

  return;
}

int main() {
  cin >> w >> h >> n;

  char input;
  for (int i = 0; i < w; ++i) {
    for (int j = 0; j < h; ++j) {
      cin >> input;
      if (input == 'X')
        map[i][j] = false;
      else
        map[i][j] = true;
      if (input == 'S')
        last_start = make_pair(i, j);
      if (input != 'X' && input != 'S' && input != '.') {
        cheese[input - '0'] = make_pair(i, j);
      }
    }
  }

  result = 0;
  for (int i = 1; i <= n; ++i) {
    init(i);
    myqueue.push(start);
    visited[start.first][start.second] = 0;

    while (!myqueue.empty()) {

      /*for(int k=0; k<w; ++k){
          for(int j=0; j<h; ++j){

              cout << visited[k][j] << " ";

          }
          cout << endl;
      }
      cout << endl;*/

      cur = myqueue.front();
      myqueue.pop();

      if (cur == goal) {
        // cout << "goal " << cur.first << " , " << cur.second << "\\n";
        break;
      }

      // visited[cur.first][cur.second] = 0;

      int x = cur.first, y = cur.second;
      if (x - 1 >= 0 && visited[x - 1][y] == INF) {
        myqueue.push(make_pair(x - 1, y));
        visited[x - 1][y] = visited[x][y] + 1;
      }
      if (y - 1 >= 0 && visited[x][y - 1] == INF) {
        myqueue.push(make_pair(x, y - 1));
        visited[x][y - 1] = visited[x][y] + 1;
      }
      if (x + 1 < w && visited[x + 1][y] == INF) {
        myqueue.push(make_pair(x + 1, y));
        visited[x + 1][y] = visited[x][y] + 1;
      }
      if (y + 1 < h && visited[x][y + 1] == INF) {
        myqueue.push(make_pair(x, y + 1));
        visited[x][y + 1] = visited[x][y] + 1;
      }
    }

    result += visited[goal.first][goal.second];
    // cout << visited[goal.first][goal.second] << endl;
    last_start = goal;
  }

  cout << result << endl;
  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(node st, char ed) {
  queue<node> que;
  que.push(st);
  vis[st.x][st.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 >= w || x < 0 || y >= h || 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", &w, &h, &n)) {
    for (int i = 0; i < w; i++) {
      cin >> ma[i];
      for (int j = 0; j < h; j++)
        if (ma[i][j] == 'S') {
          start.x = i;
          start.y = j;
          start.time = 0;
          ma[i][j] = '0';
        }
    }
    for (int i = 0; i < n; i++) {
      memset(vis, 0, sizeof(vis));
      bfs(start, i + '1');
    }

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

#include <iostream>
#include <queue>
using namespace std;
int w, h, n;
char map[1024][1024];
int d[1024][1024];
const int direction[4][2] = {
    {-1, 0},
    {1, 0},
    {0, -1},
    {0, 1},
};

int factory[16][2];
typedef pair<int, int> P;

int bfs(const int &sx, const int &sy, const int &gx, const int &gy) {
  // memset(d, -1, sizeof(d));
  for (int i = 0; i < h; ++i) {
    for (int j = 0; j < w; ++j) {
      d[j][i] = -1;
    }
  }
  queue<P> que;
  que.push(P(sx, sy));
  d[sx][sy] = 0;
  while (que.size()) {
    const P p = que.front();
    que.pop();
    // 如果是?点就?束
    if (p.first == gx && p.second == gy) {
      break;
    }

    // 四方向漫游
    for (int i = 0; i < 4; ++i) {
      int nx = p.first + direction[i][0];
      int ny = p.second + direction[i][1];
      // 是否可以移?，并且?点没有???
      if (0 <= nx && nx < w && 0 <= ny && ny < h && map[nx][ny] != 'X' &&
          d[nx][ny] == -1) {
        que.push(P(nx, ny));
        d[nx][ny] = d[p.first][p.second] + 1;
      }
    }
  }

  return d[gx][gy];
}

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

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

  for (int i = 0; i < h; ++i) {
    for (int j = 0; j < w; ++j) {
      if (map[j][i] == 'S') {
        factory[0][0] = j;
        factory[0][1] = i;
        map[j][i] = '.';
      } else if (isdigit(map[j][i])) {
        int index = map[j][i] - '0';
        factory[index][0] = j;
        factory[index][1] = i;
      }
    }
  }

  int step = 0;
  for (int i = 0; i < n; ++i) {

    step +=
        bfs(factory[i][0], factory[i][1], factory[i + 1][0], factory[i + 1][1]);
  }

  cout << step << endl;

  return 0;
}


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

struct P {
  int x;
  int y;
  int dist;
  P() {}
  ~P() {}
  P(const P &r) : x(r.x), y(r.y), dist(r.dist) {}
  P(int a, int b, int c) : x(a), y(b), dist(c) {}
};

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

int H, W, N;
char field[1000][1010];
char poyo[1000][1010];
queue<P> que;

int main() {
  while (scanf("%d%d%d", &H, &W, &N) != EOF) {
    for (int x = 0; x < H; x++) {
      scanf(" %s", field[x]);
    }
    P path[10];
    for (int x = 0; x < H; x++) {
      for (int y = 0; y < W; y++) {
        if (field[x][y] == 'S') {
          path[0] = P(x, y, 0);
        }
        if ('1' <= field[x][y] && field[x][y] <= '9') {
          path[field[x][y] - '0'] = P(x, y, 0);
        }
      }
    }
    int ans = 0;
    for (int x = 0; x < N; x++) {
      while (!que.empty())
        que.pop();
      for (int w = 0; w < H; w++) {
        for (int z = 0; z < W; z++) {
          poyo[w][z] = field[w][z];
        }
      }
      que.push(P(path[x].x, path[x].y, 0));
      bool found = false;
      while (!found && !que.empty()) {
        P p = que.front();
        que.pop();
        for (int z = 0; z < 4; z++) {
          int nx = p.x + dx[z];
          int ny = p.y + dy[z];
          if (0 > nx || nx >= H || 0 > ny || ny >= W || poyo[nx][ny] == 'X')
            continue;
          if (poyo[nx][ny] == '0' + x + 1) {
            ans += p.dist + 1;
            found = true;
            break;
          }
          que.push(P(nx, ny, p.dist + 1));
        }
        poyo[p.x][p.y] = 'X';
      }
    }
    printf("%d\\n", ans);
    break;
  }
  return 0;
}

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

struct P {
  int x, y, dist;
  P() {}
  ~P() {}
  P(const P &r) : x(r.x), y(r.y), dist(r.dist) {}
  P(int a, int b, int d) : x(a), y(b), dist(d) {}
};

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

int H, W, N;
char field[1000][1010], cpy[1000][1010];

queue<P> que;

int main() {
  while (scanf("%d%d%d", &H, &W, &N) != EOF) {
    for (int x = 0; x < H; ++x) {
      scanf(" %s", field[x]);
    }
    P loc[10];
    for (int x = 0; x < H; ++x) {
      for (int y = 0; y < W; ++y) {
        if (field[x][y] == 'S') {
          loc[0] = P(x, y, 0);
        }
        if ('1' <= field[x][y] && field[x][y] <= '9') {
          loc[field[x][y] - '0'] = P(x, y, 0);
        }
      }
    }
    int ans = 0;
    for (int n = 0; n < N; ++n) {
      for (int x = 0; x < H; ++x) {
        for (int y = 0; y < W; ++y) {
          cpy[x][y] = field[x][y];
        }
      }
      while (!que.empty())
        que.pop();
      que.push(loc[n]);
      cpy[loc[n].x][loc[n].y] = 'X';
      while (!que.empty()) {
        P p = que.front();
        que.pop();
        if (p.x == loc[n + 1].x && p.y == loc[n + 1].y) {
          ans += p.dist;
          break;
        }
        for (int i = 0; i < 4; ++i) {
          int nx = p.x + dx[i], ny = p.y + dy[i];
          if (nx < 0 || H <= nx)
            continue;
          if (ny < 0 || W <= ny)
            continue;
          if (cpy[nx][ny] == 'X')
            continue;
          que.push(P(nx, ny, p.dist + 1));
          cpy[nx][ny] = 'X';
        }
      }
    }
    printf("%d\\n", ans);
  }
  return 0;
}


#include <cstdio>
#include <iostream>
#include <queue>
#include <stack>

using namespace std;
const int maxn = 1005;
const int inf = 1e6;

typedef pair<int, int> P;
char data[maxn][maxn];
int dist[maxn][maxn];
int sx, sy, w, h, n, energy, sum;

void bfs(int &sx, int &sy, int energy) {
  int a[4] = {-1, 0, 1, 0}, b[4] = {0, -1, 0, 1};
  queue<P> que;
  que.push(P(sx, sy));
  char temp[h][w];
  for (int i = 0; i < h; ++i) {
    for (int j = 0; j < w; ++j) {
      dist[i][j] = inf;
      temp[i][j] = data[i][j];
    }
  }

  dist[sx][sy] = 0;

  while (!que.empty()) {
    P cur = que.front();
    que.pop();
    int x = cur.first, y = cur.second;
    if (temp[x][y] == (energy + '0')) {
      sx = x;
      sy = y;
      return;
    }

    temp[x][y] = 'X';
    for (int i = 0; i < 4; ++i) {
      int nx = x + a[i], ny = y + b[i];
      if (nx >= 0 && nx < h && ny >= 0 && ny < w && temp[nx][ny] != 'X') {
        que.push(P(nx, ny));
        dist[nx][ny] = min(dist[nx][ny], dist[x][y] + 1);
      }
    }
  }
}

int main() {
  // while(scanf("%d%d", &w, &h)!= EOF && w && h){
  scanf("%d%d%d", &h, &w, &n);
  for (int i = 0; i < h; ++i)
    scanf("%s", &data[i]);

  for (int i = 0; i < h; ++i) {
    for (int j = 0; j < w; ++j) {
      if (data[i][j] == 'S') {
        sx = i;
        sy = j;
      }
    }
  }
  sum = 0, energy = 1;
  while (energy <= n) {
    int bx = sx, by = sy;
    bfs(sx, sy, energy);
    data[bx][by] = '.';
    sum += dist[sx][sy];
    ++energy;
  }
  printf("%d\\n", sum);

  //}
  return 0;
}

#include <cstdio>
#include <iostream>
#include <queue>
#include <stack>

using namespace std;
const int maxn = 1005;
const int inf = 1e6;

typedef pair<int, int> P;
char data[maxn][maxn];
int dist[maxn][maxn];
int sx, sy, w, h, n, sum;
P fac[15];

void initialize() {
  for (int i = 0; i < h; ++i) {
    for (int j = 0; j < w; ++j) {
      dist[i][j] = inf;
    }
  }
}

void bfs(P s, P g) {
  int a[4] = {-1, 0, 1, 0}, b[4] = {0, -1, 0, 1};
  queue<P> que;
  que.push(s);

  while (!que.empty()) {
    P cur = que.front();
    que.pop();

    if (cur == g)
      return;

    int x = cur.first, y = cur.second;
    for (int i = 0; i < 4; ++i) {
      int nx = x + a[i], ny = y + b[i];
      if (nx >= 0 && nx < h && ny >= 0 && ny < w && data[nx][ny] != 'X' &&
          dist[nx][ny] == inf) {
        que.push(P(nx, ny));
        dist[nx][ny] = min(dist[nx][ny], dist[x][y] + 1);
      }
    }
  }
}

int main() {
  // while(scanf("%d%d", &w, &h)!= EOF && w && h){
  scanf("%d%d%d", &h, &w, &n);
  for (int i = 0; i < h; ++i)
    scanf("%s", &data[i]);

  for (int i = 0; i < h; ++i) {
    for (int j = 0; j < w; ++j) {
      if (data[i][j] == 'S') {
        fac[0] = P(i, j);
      } else if (data[i][j] >= '1' && data[i][j] <= '9')
        fac[data[i][j] - '0'] = P(i, j);
    }
  }
  sum = 0;
  for (int i = 1; i <= n; ++i) {
    int x = fac[i - 1].first, y = fac[i - 1].second;
    initialize();
    dist[x][y] = 0;
    bfs(fac[i - 1], fac[i]);
    // data[x][y] = '.';
    sum += dist[fac[i].first][fac[i].second];
    // cout << sum << endl;
  }
  printf("%d\\n", sum);

  //}
  return 0;
}


// AOJ 0558
#include <cstdio>
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <vector>
#define REP(i, n) for (int i = 0; i < (int)(n); i++)
#define X first
#define Y second
using namespace std;

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

int H, W, N;
const int HMAX = 1008, WMAX = 1008;
char field[HMAX][WMAX];

bool legal(P p) { return 0 <= p.X and p.X < W and 0 <= p.Y and p.Y < H; }

int dist(P start, P goal) {
  priority_queue<S, vector<S>, greater<S>> que;
  que.push(S(0, start));
  while (!que.empty()) {
    S s = que.top();
    que.pop();
    P cur = s.second;

    if (cur.X == goal.X and cur.Y == goal.Y) {
      return s.first;
    }

    const int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, -1, 0, 1};
    REP(i, 4) {
      P p = P(cur.X + dx[i], cur.Y + dy[i]);
      if (legal(p) and field[p.X][p.Y] != 'X') {
        que.push(S(s.first + 1, p));
      }
    }
  }
}

P search(char c) {
  REP(y, H) REP(x, W) {
    if (field[x][y] == c)
      return P(x, y);
  }
}

int solve() {
  int ans = 0;
  P start = search('S');
  for (int i = 1; i <= N; i++) {
    P goal = search('0' + i);
    ans += dist(start, goal);
    start = goal;
  }
  return ans;
}

int main() {
  cin >> H >> W >> N;
  REP(y, H) {
    string row;
    cin >> row;
    REP(x, W) { field[x][y] = row[x]; }
  }

  cout << solve() << endl;
}

// AOJ 0558
#include <cstdio>
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <vector>
#define REP(i, n) for (int i = 0; i < (int)(n); i++)
#define X first
#define Y second
using namespace std;

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

int H, W, N;
const int HMAX = 1008, WMAX = 1008;
char field[HMAX][WMAX];

bool legal(P p) {
  return 0 <= p.X and p.X < W and 0 <= p.Y and p.Y < H and
         field[p.X][p.Y] != 'X';
}

const int INF = 1e7;
int dist[HMAX][WMAX];

int distance(P start, P goal) {
  priority_queue<S, vector<S>, greater<S>> que;
  REP(x, W) REP(y, H) { dist[x][y] = INF; }

  dist[start.X][start.Y] = 0;
  que.push(S(0, start));

  while (!que.empty()) {
    S state = que.top();
    que.pop();
    P cur = state.second;
    if (dist[cur.X][cur.Y] < state.first)
      continue;

    const int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};
    REP(i, 4) {
      P p = P(cur.X + dx[i], cur.Y + dy[i]);
      if (legal(p) and dist[p.X][p.Y] > dist[cur.X][cur.Y] + 1) {
        dist[p.X][p.Y] = dist[cur.X][cur.Y] + 1;
        que.push(S(dist[p.X][p.Y], p));
      }
    }
  }
  return dist[goal.X][goal.Y];
}

P search(char c) {
  REP(y, H) REP(x, W) {
    if (field[x][y] == c)
      return P(x, y);
  }
}

int solve() {
  int ans = 0;
  P start = search('S');
  for (int i = 1; i <= N; i++) {
    P goal = search('0' + i);
    ans += distance(start, goal);
    start = goal;
  }
  return ans;
}

int main() {
  cin >> H >> W >> N;
  REP(y, H) {
    string row;
    cin >> row;
    REP(x, W) { field[x][y] = row[x]; }
  }

  cout << solve() << endl;
}


#include <algorithm>
#include <cassert>
#include <cctype>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <vector>

using namespace std;

#define all(c) ((c).begin()), ((c).end())
#define dump(c) cerr << "> " << #c << " = " << (c) << endl;
#define iter(c) __typeof((c).begin())
#define tr(i, c) for (iter(c) i = (c).begin(); i != (c).end(); i++)
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define repi(i, a, b) for (int i = (int)(a); i <= (int)(b); i++)

#define mp make_pair
#define fst first
#define snd second
#define pb push_back

typedef unsigned int uint;
typedef long long ll;
typedef unsigned long long ull;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<double> vd;
typedef vector<vd> vvd;
typedef vector<string> vs;
typedef pair<int, int> pii;

const int INF = 1 << 29;
const double EPS = 1e-10;

template <typename T1, typename T2>
ostream &operator<<(ostream &os, const pair<T1, T2> &p) {
  return os << '(' << p.first << ',' << p.second << ')';
}
template <typename T> ostream &operator<<(ostream &os, const vector<T> &a) {
  os << '[';
  rep(i, a.size()) os << (i ? " " : "") << a[i];
  return os << ']';
}

typedef pair<int, pair<int, pii>> State;

int H, W, N;
char m[1010][1010];

int main() {
  cin >> H >> W >> N;
  pii start;
  rep(i, H) rep(j, W) {
    cin >> m[i][j];
    if (m[i][j] == 'S') {
      start.fst = j;
      start.snd = i;
    }
  }

  priority_queue<State, vector<State>, greater<State>> q;
  q.push(mp(0, mp(0, start)));
  map<pair<int, pii>, bool> visited;

  while (!q.empty()) {
    State st = q.top();
    q.pop();
    if (visited[st.snd])
      continue;
    visited[st.snd] = true;

    int x = st.snd.snd.fst, y = st.snd.snd.snd;
    int ate = st.snd.fst;
    if (__builtin_popcount(ate) == N) {
      cout << st.fst << endl;
      break;
    }
    static const int dx[] = {1, 0, -1, 0};
    static const int dy[] = {0, 1, 0, -1};
    rep(d, 4) {
      int tx = x + dx[d];
      int ty = y + dy[d];
      if (tx < 0 || tx >= W || ty < 0 || ty >= H)
        continue;
      if (m[ty][tx] == 'X')
        continue;
      if (isdigit(m[ty][tx])) {
        if (ate & 1 << m[ty][tx] - '0')
          continue;
        int hp = 1 + __builtin_popcount(ate);
        if (hp >= m[ty][tx] - '0') {
          q.push(mp(st.fst + 1, mp(ate | 1 << m[ty][tx] - '0', mp(tx, ty))));
          continue;
        }
      }
      q.push(mp(st.fst + 1, mp(ate, mp(tx, ty))));
    }
  }

  return 0;
}

#include <algorithm>
#include <cassert>
#include <cctype>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <vector>

using namespace std;

#define all(c) ((c).begin()), ((c).end())
#define dump(c) cerr << "> " << #c << " = " << (c) << endl;
#define iter(c) __typeof((c).begin())
#define tr(i, c) for (iter(c) i = (c).begin(); i != (c).end(); i++)
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define repi(i, a, b) for (int i = (int)(a); i <= (int)(b); i++)

#define mp make_pair
#define fst first
#define snd second
#define pb push_back

typedef unsigned int uint;
typedef long long ll;
typedef unsigned long long ull;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<double> vd;
typedef vector<vd> vvd;
typedef vector<string> vs;
typedef pair<int, int> pii;

const int INF = 1 << 29;
const double EPS = 1e-10;

template <typename T1, typename T2>
ostream &operator<<(ostream &os, const pair<T1, T2> &p) {
  return os << '(' << p.first << ',' << p.second << ')';
}
template <typename T> ostream &operator<<(ostream &os, const vector<T> &a) {
  os << '[';
  rep(i, a.size()) os << (i ? " " : "") << a[i];
  return os << ']';
}

typedef pair<int, pii> State;

int H, W, N;
char m[1010][1010];

vi bfs(int x, int y) {
  vi res(N + 1, 0);

  queue<pair<int, pii>> q;
  q.push(mp(0, mp(x, y)));
  map<pii, bool> visited;

  while (!q.empty()) {
    pair<int, pii> p = q.front();
    q.pop();
    if (visited[p.snd])
      continue;
    visited[p.snd] = true;

    if (isdigit(m[p.snd.snd][p.snd.fst])) {
      res[m[p.snd.snd][p.snd.fst] - '0'] = p.fst;
    }
    if (m[p.snd.snd][p.snd.fst] == 'S') {
      res[0] = p.fst;
    }

    static const int dx[] = {1, 0, -1, 0};
    static const int dy[] = {0, 1, 0, -1};
    rep(d, 4) {
      int tx = p.snd.fst + dx[d];
      int ty = p.snd.snd + dy[d];
      if (tx < 0 || tx >= W || ty < 0 || ty >= H)
        continue;
      if (m[ty][tx] == 'X')
        continue;
      q.push(mp(p.fst + 1, mp(tx, ty)));
    }
  }

  return res;
}

int main() {
  cin >> H >> W >> N;
  pii start;
  rep(i, H) rep(j, W) {
    cin >> m[i][j];
    if (m[i][j] == 'S') {
      start.fst = j;
      start.snd = i;
    }
  }

  vvi mt(N + 1);
  rep(i, H) rep(j, W) {
    if (isdigit(m[i][j]))
      mt[m[i][j] - '0'] = bfs(j, i);
    else if (m[i][j] == 'S')
      mt[0] = bfs(j, i);
  }

  priority_queue<State, vector<State>, greater<State>> q;
  q.push(mp(0, mp(0, 0)));
  map<pii, bool> visited;

  while (!q.empty()) {
    State st = q.top();
    q.pop();
    if (visited[st.snd])
      continue;
    visited[st.snd] = true;

    int pos = st.snd.snd;
    int ate = st.snd.fst;
    if (__builtin_popcount(ate) == N) {
      cout << st.fst << endl;
      break;
    }
    int hp = 1 + __builtin_popcount(ate);
    rep(i, N) if ((ate & 1 << i + 1) == 0) if (hp >= i + 1) {
      q.push(mp(st.fst + mt[pos][i + 1], mp(ate | 1 << i + 1, i + 1)));
    }
  }

  return 0;
}