#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <ctype.h>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>

using namespace std;

#define REP(i, x, n) for (int i = x; i < n; i++)
#define rep(i, n) REP(i, 0, n)
#define lengthof(x) (sizeof(x) / sizeof(*(x)))
#define FILL(ptr, value) FILL_((ptr), sizeof(ptr) / sizeof(value), (value))
template <typename T> void FILL_(void *ptr, size_t size, T value) {
  std::fill((T *)ptr, (T *)ptr + size, value);
}
// 4方向ベクトル→↑←↓
const int dx[] = {1, 0, -1, 0};
const int dy[] = {0, -1, 0, 1};
typedef pair<int, int> P;
const int INF = 1e+9;
int H, W, N;
int d[1010][1010];
char board[1010][1010];
int sx, sy;
int gx, gy;
int ans;
void bfs(int y, int x, int k) {
  for (int i = 1; i <= H; i++) {
    for (int j = 1; j <= W; j++) {
      d[i][j] = INF;
      if (board[i][j] == k + '0') {
        gx = j;
        gy = i;
      }
    }
  }
  d[y][x] = 0;
  queue<P> que;
  que.push(P(y, x));
  while (!que.empty()) {
    P p = que.front();
    que.pop();

    if (p.first == gy && p.second == gx)
      break;
    for (int i = 0; i < 4; i++) {
      int nx = p.second + dx[i];
      int ny = p.first + dy[i];
      if (nx >= 1 && nx <= W && ny >= 1 && ny <= H && board[ny][nx] != 'X' &&
          d[ny][nx] > d[p.first][p.second]) {
        que.push(P(ny, nx));
        d[ny][nx] = d[p.first][p.second] + 1;
      }
    }
  }
  ans += d[gy][gx];
  if (k != N)
    bfs(gy, gx, k + 1);
}

int main() {
  cin >> H >> W >> N;
  for (int i = 1; i <= H; i++) {
    for (int j = 1; j <= W; j++) {
      cin >> board[i][j];
    }
  }
  for (int i = 1; i <= H; i++) {
    for (int j = 1; j <= W; j++) {
      if (board[i][j] == 'S') {
        sx = j;
        sy = i;
      }
    }
  }
  bfs(sy, sx, 1);
  cout << ans << endl;
  return 0;
}

#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <ctype.h>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>

using namespace std;

#define REP(i, x, n) for (int i = x; i < n; i++)
#define rep(i, n) REP(i, 0, n)
#define lengthof(x) (sizeof(x) / sizeof(*(x)))
#define FILL(ptr, value) FILL_((ptr), sizeof(ptr) / sizeof(value), (value))
template <typename T> void FILL_(void *ptr, size_t size, T value) {
  std::fill((T *)ptr, (T *)ptr + size, value);
}
// 4方向ベクトル→↑←↓
const int dx[] = {1, 0, -1, 0};
const int dy[] = {0, -1, 0, 1};
typedef pair<int, int> P;
const int INF = 1e+9;
int H, W, N;
int d[1010][1010];
char board[1010][1010];
int sx, sy;
int gx, gy;
int ans;
void bfs(int y, int x, int k) {
  for (int i = 1; i <= H; i++) {
    for (int j = 1; j <= W; j++) {
      d[i][j] = INF;
      if (board[i][j] == k + '0') {
        gx = j;
        gy = i;
      }
    }
  }
  d[y][x] = 0;
  queue<P> que;
  que.push(P(y, x));
  while (!que.empty()) {
    P p = que.front();
    que.pop();

    if (p.first == gy && p.second == gx)
      break;
    for (int i = 0; i < 4; i++) {
      int nx = p.second + dx[i];
      int ny = p.first + dy[i];
      if (nx >= 1 && nx <= W && ny >= 1 && ny <= H && board[ny][nx] != 'X' &&
          d[ny][nx] == INF) {
        que.push(P(ny, nx));
        d[ny][nx] = d[p.first][p.second] + 1;
      }
    }
  }
  ans += d[gy][gx];
  if (k != N)
    bfs(gy, gx, k + 1);
}

int main() {
  cin >> H >> W >> N;
  for (int i = 1; i <= H; i++) {
    for (int j = 1; j <= W; j++) {
      cin >> board[i][j];
    }
  }
  for (int i = 1; i <= H; i++) {
    for (int j = 1; j <= W; j++) {
      if (board[i][j] == 'S') {
        sx = j;
        sy = i;
      }
    }
  }
  bfs(sy, sx, 1);
  cout << ans << endl;
  return 0;
}


#include <iostream>
#include <queue>
using namespace std;
struct dir {
  int x, y;
} dir[4] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
char hole[1005][1005], factory[10][2];
int d[1005][1005], h, w, n;
typedef pair<int, int> P;
int bfs(const int &sx, const int &sy, const int &gx, const int &gy) {
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      d[i][j] = -1;
    }
  }
  // memset(d,-1,sizeof(d));
  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 + dir[i].x;
      int ny = p.second + dir[i].y;
      if (nx >= 0 && ny >= 0 && nx < h && ny < w && hole[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];
}
int main() {
  // scanf("%d%d%d\\n",&h,&w,&n);
  cin >> h >> w >> n;
  for (int i = 0; i < h; i++)
    for (int j = 0; j < w; j++) {
      // scanf("%c",&hole[i][j]);
      cin >> hole[i][j];
      if (hole[i][j] == 'S') {
        factory[0][0] = i;
        factory[0][1] = j;
      }
      if (isdigit(hole[i][j])) {
        int index = hole[i][j] - '0';
        factory[index][0] = i;
        factory[index][1] = j;
      }
    }
  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;
  // printf("%d\\n",step);
  return 0;
}

#include <cstdio>
#include <cstring>
#include <iostream>
#include <queue>
#include <utility>
using namespace std;
struct dir {
  int x, y;
} dir[4] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
char hole[1005][1005];
int d[1005][1005], h, w, factory[10][2];
typedef pair<int, int> P;
int bfs(const int &sx, const int &sy, const int &gx, const int &gy) {
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      d[i][j] = -1;
    }
  }
  // memset(d,-1,sizeof(d));
  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 + dir[i].x;
      int ny = p.second + dir[i].y;
      if (nx >= 0 && ny >= 0 && nx < h && ny < w && hole[nx][ny] != 'X' &&
          d[nx][ny] == -1) {
        d[nx][ny] = d[p.first][p.second] + 1;
        que.push(P(nx, ny));
      }
    }
  }
  return d[gx][gy];
}
int main() {
  int sx, sy, i, j, step = 0, n;
  scanf("%d%d%d\\n", &h, &w, &n);
  // cin>>h>>w>>n;
  for (i = 0; i < h; i++, getchar())
    for (j = 0; j < w; j++) {
      scanf("%c", &hole[i][j]);
      if (hole[i][j] == 'S') {
        factory[0][0] = i;
        factory[0][1] = j;
        hole[i][j] = '.';
      }
      if (isdigit(hole[i][j])) {
        int index = hole[i][j] - '0';
        factory[index][0] = i;
        factory[index][1] = j;
      }
    }
  for (i = 0; i < n; i++)
    step +=
        bfs(factory[i][0], factory[i][1], factory[i + 1][0], factory[i + 1][1]);
  // cout<<step<<endl;
  printf("%d\\n", step);
  return 0;
}


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

#define mp make_pair
#define f first
#define s second

using namespace std;

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

const int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};
int h, w;
string grid[1000];

int bfs(P S, P G) {

  queue<T> que;
  que.push(T(0, S));

  while (!que.empty()) {
    T now = que.front();
    if (now.s.f == G.f && now.s.s == G.s)
      return now.f;
    grid[now.s.f][now.s.s] = 'X';

    que.pop();
    for (int i = 0; i < 4; i++) {
      if (0 <= now.s.f + dx[i] && 0 <= now.s.s + dy[i] && now.s.f + dx[i] < h &&
          now.s.s + dy[i] < w &&
          grid[now.s.f + dx[i]][now.s.s + dy[i]] != 'X') {
        que.push(T(now.f + 1, P(now.s.f + dx[i], now.s.s + dy[i])));
      }
    }
  }
}

int main(void) {
  int n;
  string in[1000];
  P v[1001];

  cin >> h >> w >> n;

  for (int i = 0; i < h; i++)
    cin >> in[i];

  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      if (in[i][j] == 'S')
        v[0] = mp(i, j);
      if (in[i][j] != 'X' && in[i][j] != '.')
        v[in[i][j] - '0'] = mp(i, j);
    }
  }

  int ans = 0;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < h; j++)
      grid[j] = in[j];
    ans += bfs(v[i], v[i + 1]);
  }

  cout << ans << endl;

  return 0;
}

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

#define mp make_pair
#define f first
#define s second

using namespace std;

typedef pair<int, int> P;

const int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};
int h, w;
string grid[1000];
int d[1000][1000];

void bfs(P S) {

  queue<P> que;
  que.push(S);
  d[S.f][S.s] = 0;

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

    que.pop();
    for (int i = 0; i < 4; i++) {
      if (0 <= now.f + dx[i] && 0 <= now.s + dy[i] && now.f + dx[i] < h &&
          now.s + dy[i] < w && grid[now.f + dx[i]][now.s + dy[i]] != 'X') {

        if (d[now.f][now.s] + 1 < d[now.f + dx[i]][now.s + dy[i]]) {
          d[now.f + dx[i]][now.s + dy[i]] = d[now.f][now.s] + 1;
          que.push(P(now.f + dx[i], now.s + dy[i]));
        }
      }
    }
  }
}

int main(void) {
  int n;
  P v[1001];

  cin >> h >> w >> n;

  for (int i = 0; i < h; i++)
    cin >> grid[i];

  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      if (grid[i][j] == 'S')
        v[0] = mp(i, j);
      if (grid[i][j] != 'X' && grid[i][j] != '.')
        v[grid[i][j] - '0'] = mp(i, j);
    }
  }

  int ans = 0;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < h; j++)
      for (int k = 0; k < w; k++)
        d[j][k] = 100000000;
    bfs(v[i]);
    ans += d[v[i + 1].f][v[i + 1].s];
  }

  cout << ans << endl;

  return 0;
}


#include <algorithm>
#include <cstdio>
#include <iostream>
#include <queue>
using namespace std;
struct k {
  int nx;
  int ny;
  int power;
  int nowans;
};
int fiemin[15][1003][1003];
int main() {
  int h, w, n;
  char fie[1003][1003];
  for (int i = 0; i < 15; i++) {
    for (int j = 0; j < 1003; j++) {
      for (int k = 0; k < 1003; k++) {
        fiemin[i][j][k] = 2100000000;
      }
    }
  }
  for (int j = 0; j < 1003; j++) {
    for (int k = 0; k < 1003; k++) {
      fie[j][k] = 'X';
    }
  }
  int nx, ny, po, judge;
  struct k now;
  queue<k> que;
  scanf("%d %d %d", &h, &w, &n);
  for (int i = 0; i < h; i++)
    scanf("%s", &fie[i]);
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      if (fie[i][j] == 'S') {
        now.ny = i, now.nx = j, now.power = 0, now.nowans = 0;
        fie[i][j] = '.';
        goto a;
      }
    }
  }
a:
  que.push(now);
  for (int i = 0;; i++) {
    now = que.front(), que.pop();

    // printf("[%d][%d][%d][%d]\\n",now.nx,now.ny,now.nowans,now.power);

    if (now.power == n) {
      printf("%d\\n", now.nowans);
      break;
    }
    if (0 <= now.ny - 1) {
      if (fie[now.ny - 1][now.nx] == now.power + 1 + '0') {
        if (now.nowans + 1 < fiemin[now.power + 1][now.ny - 1][now.nx]) {
          while (!que.empty())
            que.pop();
          now.ny--, now.power++, now.nowans++;
          que.push(now);
          fiemin[now.power + 1][now.ny][now.nx] = now.nowans;
          now.ny++, now.power--, now.nowans--;
        }
      } else if (fie[now.ny - 1][now.nx] != 'X') {
        if (now.nowans + 1 < fiemin[now.power][now.ny - 1][now.nx]) {
          now.ny--, now.nowans++;
          que.push(now);
          fiemin[now.power][now.ny][now.nx] = now.nowans;
          now.ny++, now.nowans--;
        }
      }
    }
    if (now.nx + 1 < w) {
      if (fie[now.ny][now.nx + 1] == now.power + 1 + '0') {
        if (now.nowans + 1 < fiemin[now.power + 1][now.ny][now.nx + 1]) {
          while (!que.empty())
            que.pop();
          now.nx++, now.power++, now.nowans++;
          que.push(now);
          fiemin[now.power + 1][now.ny][now.nx] = now.nowans;
          now.nx--, now.power--, now.nowans--;
        }
      } else if (fie[now.ny][now.nx + 1] != 'X') {
        if (now.nowans + 1 < fiemin[now.power][now.ny][now.nx + 1]) {
          now.nx++, now.nowans++;
          que.push(now);
          fiemin[now.power][now.ny][now.nx] = now.nowans;
          now.nx--, now.nowans--;
        }
      }
    }
    if (now.ny + 1 < h) {
      if (fie[now.ny + 1][now.nx] == now.power + 1 + '0') {
        if (now.nowans + 1 < fiemin[now.power + 1][now.ny + 1][now.nx]) {
          while (!que.empty())
            que.pop();
          now.ny++, now.power++, now.nowans++;
          que.push(now);
          fiemin[now.power + 1][now.ny][now.nx] = now.nowans;
          now.ny--, now.power--, now.nowans--;
        }
      } else if (fie[now.ny + 1][now.nx] != 'X') {
        if (now.nowans + 1 < fiemin[now.power][now.ny + 1][now.nx]) {
          now.ny++, now.nowans++;
          que.push(now);
          fiemin[now.power][now.ny][now.nx] = now.nowans;
          now.ny--, now.nowans--;
        }
      }
    }
    if (0 <= now.nx - 1) {
      if (fie[now.ny][now.nx - 1] == now.power + 1 + '0') {
        if (now.nowans + 1 < fiemin[now.power + 1][now.ny][now.nx - 1]) {
          while (!que.empty())
            que.pop();
          now.nx--, now.power++, now.nowans++;
          que.push(now);
          fiemin[now.power + 1][now.ny][now.nx] = now.nowans;
          now.nx++, now.power--, now.nowans--;
        }
      } else if (fie[now.ny][now.nx - 1] != 'X') {
        if (now.nowans + 1 < fiemin[now.power][now.ny][now.nx - 1]) {
          now.nx--, now.nowans++;
          que.push(now);
          fiemin[now.power][now.ny][now.nx] = now.nowans;
          now.nx++, now.nowans--;
        }
      }
    }
  }
  return 0;
}

#include <algorithm>
#include <cstdio>
#include <iostream>
#include <queue>
using namespace std;
struct k {
  int nx;
  int ny;
  int power;
  int nowans;
};
int fiemin[15][1003][1003];
int main() {
  int h, w, n;
  const int dx[4] = {0, 1, 0, -1}, dy[4] = {-1, 0, 1, 0};
  char fie[1003][1003];
  for (int i = 0; i < 15; i++) {
    for (int j = 0; j < 1003; j++) {
      for (int k = 0; k < 1003; k++) {
        fiemin[i][j][k] = 2100000000;
      }
    }
  }
  for (int j = 0; j < 1003; j++) {
    for (int k = 0; k < 1003; k++) {
      fie[j][k] = 'X';
    }
  }
  k now;
  queue<k> que;
  scanf("%d %d %d", &h, &w, &n);
  for (int i = 0; i < h; i++)
    scanf("%s", &fie[i]);
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      if (fie[i][j] == 'S') {
        now.ny = i, now.nx = j, now.power = 0, now.nowans = 0;
        fie[i][j] = '.';
        goto a;
      }
    }
  }
a:
  que.push(now);
  while (1) {
    now = que.front(), que.pop();

    // printf("[%d][%d][%d][%d]\\n",now.nx,now.ny,now.nowans,now.power);

    if (now.power == n) {
      printf("%d\\n", now.nowans);
      break;
    }
    /*
    for(int i=0;i<4;i++){
        if(0<=now.nx+dx[i]&&now.nx+dx[i]<w&&0<=now.ny+dy[i]&&now.ny+dy[i]<h){
            if(fie[now.nx+dx[i]][now.ny+dy[i]]==now.power+1+'0'){
                if(now.nowans+1<fiemin[now.power+1][now.ny+dy[i][now.nx+dx[i]){
                    while(!que.empty())
                        que.pop();
                    now.nx+=dx[i],now.ny+=dy[i],now.power++,now.nowans++;
                    que.push(now);
                    fiemin[now.power][][]=now.nowans;
                }
            }
        }
    }
    */

    if (0 <= now.ny - 1) {
      if (fie[now.ny - 1][now.nx] == now.power + 1 + '0') {
        if (now.nowans + 1 < fiemin[now.power + 1][now.ny - 1][now.nx]) {
          while (!que.empty())
            que.pop();
          now.ny--, now.power++, now.nowans++;
          que.push(now);
          fiemin[now.power][now.ny][now.nx] = now.nowans;
          now.ny++, now.power--, now.nowans--;
        }
      } else if (fie[now.ny - 1][now.nx] != 'X') {
        if (now.nowans + 1 < fiemin[now.power][now.ny - 1][now.nx]) {
          now.ny--, now.nowans++;
          que.push(now);
          fiemin[now.power][now.ny][now.nx] = now.nowans;
          now.ny++, now.nowans--;
        }
      }
    }
    if (now.nx + 1 < w) {
      if (fie[now.ny][now.nx + 1] == now.power + 1 + '0') {
        if (now.nowans + 1 < fiemin[now.power + 1][now.ny][now.nx + 1]) {
          while (!que.empty())
            que.pop();
          now.nx++, now.power++, now.nowans++;
          que.push(now);
          fiemin[now.power][now.ny][now.nx] = now.nowans;
          now.nx--, now.power--, now.nowans--;
        }
      } else if (fie[now.ny][now.nx + 1] != 'X') {
        if (now.nowans + 1 < fiemin[now.power][now.ny][now.nx + 1]) {
          now.nx++, now.nowans++;
          que.push(now);
          fiemin[now.power][now.ny][now.nx] = now.nowans;
          now.nx--, now.nowans--;
        }
      }
    }
    if (now.ny + 1 < h) {
      if (fie[now.ny + 1][now.nx] == now.power + 1 + '0') {
        if (now.nowans + 1 < fiemin[now.power + 1][now.ny + 1][now.nx]) {
          while (!que.empty())
            que.pop();
          now.ny++, now.power++, now.nowans++;
          que.push(now);
          fiemin[now.power][now.ny][now.nx] = now.nowans;
          now.ny--, now.power--, now.nowans--;
        }
      } else if (fie[now.ny + 1][now.nx] != 'X') {
        if (now.nowans + 1 < fiemin[now.power][now.ny + 1][now.nx]) {
          now.ny++, now.nowans++;
          que.push(now);
          fiemin[now.power][now.ny][now.nx] = now.nowans;
          now.ny--, now.nowans--;
        }
      }
    }
    if (0 <= now.nx - 1) {
      if (fie[now.ny][now.nx - 1] == now.power + 1 + '0') {
        if (now.nowans + 1 < fiemin[now.power + 1][now.ny][now.nx - 1]) {
          while (!que.empty())
            que.pop();
          now.nx--, now.power++, now.nowans++;
          que.push(now);
          fiemin[now.power][now.ny][now.nx] = now.nowans;
          now.nx++, now.power--, now.nowans--;
        }
      } else if (fie[now.ny][now.nx - 1] != 'X') {
        if (now.nowans + 1 < fiemin[now.power][now.ny][now.nx - 1]) {
          now.nx--, now.nowans++;
          que.push(now);
          fiemin[now.power][now.ny][now.nx] = now.nowans;
          now.nx++, now.nowans--;
        }
      }
    }
  }
  return 0;
}


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

typedef pair<int, int> Pair;
const int INF = 100000000;

int H, W, N;

const int MAX_H = 1000, MAX_W = 1000;
char plant[MAX_H][MAX_W];
int sx, sy;
int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};
int d[MAX_H][MAX_W];
int mytime;

void bfs() {
  queue<Pair> que;
  for (int i = 0; i < H; i++) {
    for (int j = 0; j < W; j++) {
      d[i][j] = INF;
    }
  }
  char muscle = '1';
  que.push(Pair(sx, sy));
  d[sx][sy] = 0;
  while (que.size()) {
    Pair p = que.front();
    que.pop();
    if (int(muscle) - 48 - 1 == N)
      break;
    for (int i = 0; i < 4; i++) {
      int nx = p.first + dx[i], ny = p.second + dy[i];
      if (0 <= nx && nx < H && 0 <= ny && ny < W && plant[nx][ny] != 'X' &&
          d[nx][ny] == INF) {
        que.push(Pair(nx, ny));
        d[nx][ny] = d[p.first][p.second] + 1;
      }
      if (muscle == plant[nx][ny]) {
        while (que.size()) {
          que.pop();
        }
        que.push(Pair(nx, ny));
        muscle = muscle + 1;
        mytime += d[nx][ny];
        for (int i = 0; i < H; i++) {
          for (int j = 0; j < W; j++) {
            d[i][j] = INF;
          }
        }
        d[nx][ny] = 0;
        break;
      }
    }
  }
}

void solve() {
  mytime = 0;
  bfs();
  // printf("%d\\n", mytime);
  cout << mytime << endl;
}

int main() {
  cin >> H >> W >> N;
  // scanf("%d%d%d", &H, &W, &N);
  for (int i = 0; i < H; i++) {
    // scanf("%s", plant[i]);
    for (int j = 0; j < W; j++) {
      cin >> plant[i][j];
      if (plant[i][j] == 'S') {
        sx = i;
        sy = j;
      }
    }
  }
  solve();
}

#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;

//************************************
// Method:    bfs
// FullName:  bfs
// Access:    public
// Returns:   int
// Qualifier:
// Parameter: const int & sx 起点x
// Parameter: const int & sy 起点y
// Parameter: const int & gx 终点x
// Parameter: const int & gy 终点y
//************************************
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 <iostream>
#include <queue>
#include <utility>
using namespace std;

typedef pair<int, int> Pair;
const int INF = 100000000;

int H, W;
char N;
const int MAX_H = 1000, MAX_W = 1000;
char plant[MAX_H][MAX_W];
int sx, sy;
int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};
int d[MAX_H][MAX_W];
int mytime;

void bfs() {
  queue<Pair> que;
  for (int i = 0; i < H; i++) {
    for (int j = 0; j < W; j++) {
      d[i][j] = INF;
    }
  }
  char muscle = '1';
  que.push(Pair(sx, sy));
  d[sx][sy] = 0;
  while (que.size()) {
    Pair p = que.front();
    que.pop();
    if (muscle - 1 == N)
      break;
    for (int i = 0; i < 4; i++) {
      int nx = p.first + dx[i], ny = p.second + dy[i];
      if (0 <= nx && nx < H && 0 <= ny && ny < W && plant[nx][ny] != 'X' &&
          d[nx][ny] == INF) {
        que.push(Pair(nx, ny));
        d[nx][ny] = d[p.first][p.second] + 1;
      }
      if (muscle == plant[nx][ny]) {
        while (que.size()) {
          que.pop();
        }
        que.push(Pair(nx, ny));
        muscle = muscle + 1;
        mytime += d[nx][ny];
        for (int i = 0; i < H; i++) {
          for (int j = 0; j < W; j++) {
            d[i][j] = INF;
          }
        }
        d[nx][ny] = 0;
        break;
      }
    }
  }
}

void solve() {
  mytime = 0;
  bfs();
  cout << mytime << endl;
}

int main() {
  cin >> H >> W >> N;
  for (int i = 0; i < H; i++) {
    for (int j = 0; j < W; j++) {
      cin >> plant[i][j];
      if (plant[i][j] == 'S') {
        sx = i;
        sy = j;
      }
    }
  }
  solve();
}

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

typedef pair<int, int> Pair;
const int INF = 100000000;

int H, W;
char N;
const int MAX_H = 1010, MAX_W = 1010;
char plant[MAX_H][MAX_W];
int sx, sy;
int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};
int d[MAX_H][MAX_W];
int mytime;

void bfs() {
  queue<Pair> que;
  for (int i = 0; i < H; i++) {
    for (int j = 0; j < W; j++) {
      d[i][j] = INF;
    }
  }
  char muscle = '1';
  que.push(Pair(sx, sy));
  d[sx][sy] = 0;
  while (que.size()) {
    Pair p = que.front();
    que.pop();
    if (muscle - 1 == N)
      break;
    for (int i = 0; i < 4; i++) {
      int nx = p.first + dx[i], ny = p.second + dy[i];
      if (0 <= nx && nx < H && 0 <= ny && ny < W && plant[nx][ny] != 'X' &&
          d[nx][ny] == INF) {
        que.push(Pair(nx, ny));
        d[nx][ny] = d[p.first][p.second] + 1;
      }
      if (muscle == plant[nx][ny]) {
        while (que.size()) {
          que.pop();
        }
        que.push(Pair(nx, ny));
        muscle = muscle + 1;
        mytime += d[nx][ny];
        for (int i = 0; i < H; i++) {
          for (int j = 0; j < W; j++) {
            d[i][j] = INF;
          }
        }
        d[nx][ny] = 0;
        break;
      }
    }
  }
}

void solve() {
  mytime = 0;
  bfs();
  cout << mytime << endl;
}

int main() {
  std::ios::sync_with_stdio(false);
  std::cin.tie(0);
  // IO
  cin >> H >> W >> N;
  for (int i = 0; i < H; i++) {
    for (int j = 0; j < W; j++) {
      cin >> plant[i][j];
      if (plant[i][j] == 'S') {
        sx = i;
        sy = j;
      }
    }
  }
  solve();
}

// 错误版本突然又正确了，这是什么情况啊？？？？？？？！！！！！！！！


#include <cstdio>
#include <iostream>
#include <queue>
#define ROP(i, n) for (int i = 0; i < n; i++)
#define ROPP(i, n) for (int i = 1; i <= n; i++)
#define INF 999999999
using namespace std;
typedef pair<int, int> P;
int N, M, G, gx[10], gy[10];
char MAP[1000][1000 + 1];
int DX[4] = {1, 0, -1, 0}, DY[4] = {0, 1, 0, -1}, FAR[1000][1000 + 1];
int BFS(int u) {
  queue<P> que;
  ROPP(i, N) { ROPP(j, M) FAR[j][i] = INF; }
  que.push(P(gx[u], gy[u]));
  FAR[gx[u]][gy[u]] = 0;
  while (que.size()) {
    P p = que.front();
    que.pop();
    if (p.first == gx[u + 1] && p.second == gy[u + 1])
      break;
    ROP(i, 4) {
      int nx = p.first + DX[i], ny = p.second + DY[i];
      if (1 <= nx && nx <= M && 1 <= ny && ny <= N && MAP[nx][ny] != 'X' &&
          FAR[nx][ny] == INF) {
        que.push(P(nx, ny));
        FAR[nx][ny] = FAR[p.first][p.second] + 1;
      }
    }
  }
  return FAR[gx[u + 1]][gy[u + 1]];
}
void solve() {
  int res = 0;
  ROP(i, G) { res += BFS(i); }
  printf("%d\\n", res);
}
int main() {
  scanf("%d %d %d", &N, &M, &G);
  ROPP(i, N) {
    ROP(j, M + 1) {
      scanf("%c", &MAP[j][i]);
      if (MAP[j][i] == 'S')
        gx[0] = j, gy[0] = i;
      ROPP(k, G) {
        char l = '0' + k;
        if (MAP[j][i] == l)
          gx[k] = j, gy[k] = i;
      }
    }
  }
  solve();
  return 0;
}

#include <cstdio>
#include <iostream>
#include <queue>
#define ROP(i, n) for (int i = 0; i < n; i++)
#define ROPP(i, n) for (int i = 1; i <= n; i++)
#define INF 999999999
using namespace std;
typedef pair<int, int> P;
int N, M, G, gx[10], gy[10];
char MAP[1005][1005];
int DX[4] = {1, 0, -1, 0}, DY[4] = {0, 1, 0, -1}, FAR[1005][1005];
int BFS(int u) {
  queue<P> que;
  ROPP(i, N) { ROPP(j, M) FAR[j][i] = INF; }
  que.push(P(gx[u], gy[u]));
  FAR[gx[u]][gy[u]] = 0;
  while (que.size()) {
    P p = que.front();
    que.pop();
    if (p.first == gx[u + 1] && p.second == gy[u + 1])
      break;
    ROP(i, 4) {
      int nx = p.first + DX[i], ny = p.second + DY[i];
      if (1 <= nx && nx <= M && 1 <= ny && ny <= N && MAP[nx][ny] != 'X' &&
          FAR[nx][ny] == INF) {
        que.push(P(nx, ny));
        FAR[nx][ny] = FAR[p.first][p.second] + 1;
      }
    }
  }
  return FAR[gx[u + 1]][gy[u + 1]];
}
void solve() {
  int res = 0;
  ROP(i, G) { res += BFS(i); }
  printf("%d\\n", res);
}
int main() {
  scanf("%d %d %d", &N, &M, &G);
  ROPP(i, N) {
    ROP(j, M + 1) {
      scanf("%c", &MAP[j][i]);
      if (MAP[j][i] == 'S')
        gx[0] = j, gy[0] = i;
      ROPP(k, G) {
        char l = '0' + k;
        if (MAP[j][i] == l)
          gx[k] = j, gy[k] = i;
      }
    }
  }
  solve();
  return 0;
}


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

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

struct POS {
  int x, y;
};

int main() {
  char map[1002][1002];
  static int smp[1002][1002];
  int h, w, n, c = 0, ans, x, y;
  POS p;
  queue<pair<int, POS>> q;
  cin >> h >> w >> n;
  for (int i = 0; i < h + 2; ++i)
    for (int j = 0; j < w + 2; ++j) {
      map[i][j] = 'X';
      smp[i][j] = 100;
    }
  for (int i = 1; i <= h; ++i)
    for (int j = 1; j <= w; ++j) {
      cin >> map[i][j];
      smp[i][j] = 0;
      if (map[i][j] == 'S') {
        map[i][j] = '.';
        x = j;
        y = i;
      }
    }
  p.x = x;
  p.y = y;
  q.push(pair<int, POS>(0, p));
  while (c < n) {
    ans = q.front().first;
    x = q.front().second.x;
    y = q.front().second.y;
    q.pop();
    smp[y][x] = c + 1;
    if (map[y][x] == '1' + c) {
      c++;
      while (!q.empty())
        q.pop();
    }
    for (int i = 0; i < 4; ++i) {
      if (map[y + dy[i]][x + dx[i]] != 'X' &&
          smp[y + dy[i]][x + dx[i]] < c + 1) {
        p.x = x + dx[i];
        p.y = y + dy[i];
        q.push(pair<int, POS>(ans + 1, p));
      }
    }
  }
  cout << ans << endl;
  return 0;
}

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

#define INF 20000000

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

typedef pair<int, int> P;

int main() {
  char map[1002][1002];
  static int smp[1002][1002];
  int h, w, n, c = 0, x, y, ans = 0;
  queue<P> q;
  cin >> h >> w >> n;
  for (int i = 0; i < h + 2; ++i)
    for (int j = 0; j < w + 2; ++j) {
      map[i][j] = 'X';
      smp[i][j] = INF;
    }
  for (int i = 1; i <= h; ++i)
    for (int j = 1; j <= w; ++j) {
      cin >> map[i][j];
      smp[i][j] = INF;
      if (map[i][j] == 'S') {
        x = j;
        y = i;
      }
    }
  q.push(P(x, y));
  smp[y][x] = 0;
  while (1) {
    x = q.front().first;
    y = q.front().second;
    q.pop();
    if (map[y][x] == '1' + c) {
      ans += smp[y][x];
      c++;
      if (c == n)
        break;
      while (!q.empty())
        q.pop();
      for (int i = 1; i <= h; ++i)
        for (int j = 1; j <= w; ++j)
          smp[i][j] = INF;
      smp[y][x] = 0;
    }
    for (int i = 0; i < 4; ++i) {
      if (map[y + dy[i]][x + dx[i]] != 'X' &&
          smp[y + dy[i]][x + dx[i]] == INF) {
        q.push(P(x + dx[i], y + dy[i]));
        smp[y + dy[i]][x + dx[i]] = smp[y][x] + 1;
      }
    }
  }
  cout << ans << endl;
  return 0;
}


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

const int MAX_H = 1005;
const int MAX_W = 1005;

string all[MAX_H];
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
int h, w;
int n;
int sx, sy;
typedef pair<int, int> P;

int bfs(char target) {
  set<P> s;
  queue<P> q1;
  queue<int> q2;
  q1.push(P(sy, sx));
  q2.push(0);
  while (!q1.empty()) {
    P p = q1.front();
    q1.pop();
    int t = q2.front();
    q2.pop();
    s.insert(p);
    // cout << p.first << " " << p.second <<" "<<t<< endl;
    for (int i = 0; i < 4; ++i) {
      int y = p.first + dy[i], x = p.second + dx[i];
      if (x >= 0 && x < w && y >= 0 && y < h && all[y][x] != 'X') {
        if (s.count(P(y, x))) {
          continue;
        }
        if (all[y][x] == target) {
          all[y][x] = '.';
          sx = x, sy = y;
          return t + 1;
        } else {
          q1.push(P(y, x));
          q2.push(t + 1);
        }
      }
    }
  }
}

void solve() {
  int ans = 0;
  char t = '1';
  for (int i = 0; i < n; ++i) {
    ans += bfs(t);
    ++t;
  }
  cout << ans << endl;
}

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

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

const int MAX_H = 1005;
const int MAX_W = 1005;

string all[MAX_H];
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
int h, w;
int n;
int sx, sy;
typedef pair<int, int> P;

int bfs(char target) {
  set<P> s;
  queue<P> q1;
  queue<int> q2;
  q1.push(P(sy, sx));
  s.insert(P(sy, sx));
  q2.push(0);
  while (!q1.empty()) {
    P p = q1.front();
    q1.pop();
    int t = q2.front();
    q2.pop();
    // cout << p.first << " " << p.second <<" "<<t<< endl;
    for (int i = 0; i < 4; ++i) {
      int y = p.first + dy[i], x = p.second + dx[i];
      if (x >= 0 && x < w && y >= 0 && y < h && all[y][x] != 'X') {
        if (s.count(P(y, x))) {
          continue;
        }
        if (all[y][x] == target) {
          all[y][x] = '.';
          sx = x, sy = y;
          return t + 1;
        } else {
          q1.push(P(y, x));
          q2.push(t + 1);
          s.insert(P(y, x));
        }
      }
    }
  }
}

void solve() {
  int ans = 0;
  char t = '1';
  for (int i = 0; i < n; ++i) {
    ans += bfs(t);
    ++t;
  }
  cout << ans << endl;
}

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


#include <bits/stdc++.h>

#define FOR(i, j, k) for (int i = j; i < k; ++i)
#define rep(i, j) FOR(i, 0, j)
#define INF (1 << 30)
#define mp make_pair

using namespace std;

typedef pair<int, int> P;

const int dx[] = {0, 1, 0, -1};
const int dy[] = {1, 0, -1, 0};
int h, w, n;
int ans = 0;
int sx, sy, gx, gy;
char field[1010][1010];
bool went[1010][1010];

/*struct state{
        int x;
        int y;
        int count;
};*/

int bfs(char tmp) {
  queue<pair<int, P>> q;
  memset(went, false, sizeof(went));
  q.push(mp(0, mp(sx, sy)));

  while (!q.empty()) {
    pair<int, P> p = q.front();
    q.pop();
    // cout << p.first << " " << p.second.first << " " << p.second.second <<
    // endl;
    if ((field[p.second.second][p.second.first]) == tmp) {
      sx = p.second.first;
      sy = p.second.second;
      return p.first;
    }
    went[p.second.second][p.second.first] = true;
    rep(i, 4) {
      int nx = p.second.first + dx[i];
      int ny = p.second.second + dy[i];
      if (nx >= 0 && ny >= 0 && nx < w && ny < h && !went[ny][nx] &&
          field[ny][nx] != 'X') {
        q.push(mp(p.first + 1, mp(nx, ny)));
      }
    }
  }
  return 0;
}

int main() {
  memset(field, 0, sizeof(field));
  cin >> h >> w >> n;
  rep(i, h) rep(j, w) {
    cin >> field[i][j];
    if (field[i][j] == 'S')
      sx = j, sy = i;
    if (field[i][j] == 'G')
      gx = j, gy = i;
  }
  /*rep(i, h) {
          rep(j, w) cout << field[i][j];
          cout << endl;
  }*/
  for (int i = 1; i <= n; ++i) {
    ans += bfs('0' + i);
  }
  cout << ans << endl;
  return 0;
}

#include <iostream>
#include <map>
#include <queue>
#define INF 10000000
using namespace std;

typedef pair<int, int> P;

int H, W, N;
int d[1000][1000];
char cell[1000][1000];
int si, sj, sum = 0;

void bfs(P start, int search) {
  // 4????????¨
  int vi[4] = {0, 0, -1, 1}, vj[4] = {-1, 1, 0, 0};

  int gi, gj;

  //???????????¢???INF?????????????????????????????´???????????§?¨??????????
  for (int i = 0; i < H; i++) {
    for (int j = 0; j < W; j++) {
      d[i][j] = INF;
      if (cell[i][j] == search + '0') {
        gi = i;
        gj = j;
      }
    }
  }

  // start??????????????¢0????????????
  d[start.first][start.second] = 0;

  queue<P> que;
  que.push(start);

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

    //?????´??§break
    if (p.first == gi && p.second == gj)
      break;

    // next(i, j)
    int ni, nj;

    // 4?????????
    for (int i = 0; i < 4; i++) {
      ni = p.first + vi[i];
      nj = p.second + vj[i];

      if (ni >= 0 && ni < H && nj >= 0 && nj < W && cell[ni][nj] != 'X' &&
          d[ni][nj] == INF) {
        que.push(P(ni, nj));
        d[ni][nj] = d[p.first][p.second] + 1;
      }
    }
  }

  sum += d[gi][gj];

  if (search != N)
    bfs(P(gi, gj), search + 1);
}

int main() {
  cin >> H >> W >> N;

  for (int i = 0; i < H; i++) {
    for (int j = 0; j < W; j++) {
      cin >> cell[i][j];
      if (cell[i][j] == 'S') {
        si = i;
        sj = j;
      }
    }
  }

  bfs(P(si, sj), 1);

  cout << sum << endl;
}


#include <algorithm>
#include <climits>
#include <cmath>
#include <iostream>
#include <queue>
#include <string>
#include <vector>

using namespace std;

#define rep(i, n) for (int i = 0; i < int(n); i++)
#define all(c) (c).begin(), (c).end()

#define MAX_W 1010
#define MAX_H 1010

int H, W, N;
char A[MAX_H][MAX_W];
vector<bool **> global;

pair<int, int> find_char(char c) {
  rep(y, H) {
    rep(x, W) {
      if (A[y][x] == c)
        return make_pair(x, y);
    }
  }
  return make_pair(-1, -1);
}

bool visited[MAX_W][MAX_H];
int bfs(int start_x, int start_y, int target_x, int target_y) {
  queue<int> q;
  rep(i, W) rep(j, H) visited[i][j] = false;

  q.push(start_x);
  q.push(start_y);
  q.push(0);
  while (!q.empty()) {
    int x = q.front();
    q.pop();
    int y = q.front();
    q.pop();
    int dist = q.front();
    q.pop();

    char m = A[y][x];
    if (x == target_x && y == target_y)
      return dist;

    visited[y][x] = true;
    int dx[] = {0, 1, 0, -1};
    int dy[] = {-1, 0, 1, 0};
    rep(i, 4) {
      rep(j, 4) {
        int tx = x + dx[i];
        int ty = y + dy[i];
        if (tx >= 0 && tx < W && ty >= 0 && ty < H && A[ty][tx] != 'X') {
          if (visited[ty][tx])
            continue;
          q.push(tx);
          q.push(ty);
          q.push(dist + 1);
        }
      }
    }
  }
  return INT_MIN;
}

int main() {
  cin >> H >> W >> N;
  rep(i, H) cin >> A[i];

  // ????§???????
  auto pos_s = find_char('S');
  int start_x = pos_s.first;
  int start_y = pos_s.second;

  int ans = 0;
  for (int i = 1; i <= N; i++) {
    auto pos = find_char((char)((int)'0' + i));
    int tx = pos.first;
    int ty = pos.second;
    ans += bfs(start_x, start_y, tx, ty);

    start_x = tx;
    start_y = ty;
  }
  cout << ans << "\\n";
  return 0;
}

#include <algorithm>
#include <climits>
#include <cmath>
#include <iostream>
#include <queue>
#include <string>
#include <vector>

using namespace std;

#define rep(i, n) for (int i = 0; i < int(n); i++)
#define all(c) (c).begin(), (c).end()

#define MAX_W 1010
#define MAX_H 1010

int H, W, N;
char A[MAX_H][MAX_W];
vector<bool **> global;

pair<int, int> find_char(char c) {
  rep(y, H) {
    rep(x, W) {
      if (A[y][x] == c)
        return make_pair(x, y);
    }
  }
  return make_pair(-1, -1);
}

bool visited[MAX_W][MAX_H];
int bfs(int start_x, int start_y, int target_x, int target_y) {
  queue<int> q;
  rep(i, W) rep(j, H) visited[j][i] = false;

  q.push(start_x);
  q.push(start_y);
  q.push(0);
  while (!q.empty()) {
    int x = q.front();
    q.pop();
    int y = q.front();
    q.pop();
    int dist = q.front();
    q.pop();

    char m = A[y][x];
    if (x == target_x && y == target_y)
      return dist;

    int dx[] = {0, 1, 0, -1};
    int dy[] = {-1, 0, 1, 0};
    rep(i, 4) {
      int tx = x + dx[i];
      int ty = y + dy[i];
      if (tx >= 0 && tx < W && ty >= 0 && ty < H && A[ty][tx] != 'X' &&
          !visited[ty][tx]) {
        q.push(tx);
        q.push(ty);
        q.push(dist + 1);
        visited[ty][tx] = true;
      }
    }
  }
  return INT_MIN;
}

int main() {
  cin >> H >> W >> N;
  rep(i, H) cin >> A[i];

  // ????§???????
  auto pos_s = find_char('S');
  int start_x = pos_s.first;
  int start_y = pos_s.second;

  int ans = 0;
  for (int i = 1; i <= N; i++) {
    auto pos = find_char((char)((int)'0' + i));
    int tx = pos.first;
    int ty = pos.second;
    ans += bfs(start_x, start_y, tx, ty);
    start_x = tx;
    start_y = ty;
  }
  cout << ans << "\\n";
  return 0;
}


#include <iostream>
#include <queue>
#include <vector>

using namespace std;

vector<vector<int>> hyou(1002, vector<int>(1002, -1));
int dh[] = {0, 1, 0, -1};
int dw[] = {1, 0, -1, 0};

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

int search(int h, int w, int n) {
  int counter = 0;
  queue<Q> que;
  Q p;
  (p.second).first = h;
  (p.second).second = w;
  p.first = 0;
  que.push(p);
  while (!que.empty()) {
    Q pp = que.front();
    que.pop();
    if (hyou[(pp.second).first][(pp.second).second] == n) {
      counter = pp.first;
      break;
    } else {
      if (hyou[(pp.second).first][(pp.second).second] == 0) {
        hyou[(pp.second).first][(pp.second).second] = -2;
      }
      for (int i = 0; i < 4; i++) {
        if (hyou[(pp.second).first + dh[i]][(pp.second).second + dw[i]] != -1 &&
            hyou[(pp.second).first + dh[i]][(pp.second).second + dw[i]] != -2) {
          Q pq;
          (pq.second).first = (pp.second).first + dh[i];
          (pq.second).second = (pp.second).second + dw[i];
          pq.first = pp.first + 1;
          que.push(pq);
        }
      }
    }
  }
  for (int i = 0; i < 1002; i++) {
    for (int j = 0; j < 1002; j++) {
      if (hyou[i][j] == -2) {
        hyou[i][j] = 0;
      }
    }
  }
  return counter;
}

int main() {
  int h, w, n;
  cin >> h >> w >> n;
  char c;
  int sh, sw;
  int data[10][2];
  for (int i = 1; i <= h; i++) {
    for (int j = 1; j <= w; j++) {
      cin >> c;
      if (c == '.') {
        hyou[i][j] = 0;
      } else if (c == 'S') {
        hyou[i][j] = 0;
        sh = i;
        sw = j;
      } else if (c == 'X') {
        hyou[i][j] = -1;
      } else {
        int d = c - '0';
        hyou[i][j] = d;
        data[d - 1][0] = i;
        data[d - 1][1] = j;
      }
    }
  }
  int counter = 0;
  for (int i = 0; i < n; i++) {
    counter += search(sh, sw, i + 1);
    sh = data[i][0];
    sw = data[i][1];
  }
  cout << counter << endl;
  return 0;
}

#include <iostream>
#include <queue>
#include <vector>

using namespace std;

vector<vector<int>> hyou(1010, vector<int>(1010, -10));
int dh[] = {0, 1, 0, -1};
int dw[] = {1, 0, -1, 0};

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

int search(int h, int w, int n) {
  int counter = 0;
  queue<Q> que;
  Q p;
  (p.second).first = h;
  (p.second).second = w;
  p.first = 0;
  que.push(p);
  if (hyou[h][w] == 0) {
    hyou[h][w] = -11;
  } else {
    hyou[h][w] = -hyou[h][w];
  }
  while (!que.empty()) {
    Q pp = que.front();
    que.pop();
    bool hantei = false;
    for (int i = 0; i < 4; i++) {
      if (hyou[(pp.second).first + dh[i]][(pp.second).second + dw[i]] >= 0) {
        Q pq;
        (pq.second).first = (pp.second).first + dh[i];
        (pq.second).second = (pp.second).second + dw[i];
        pq.first = pp.first + 1;
        if (hyou[(pq.second).first][(pq.second).second] == n) {
          counter = pq.first;
          hantei = true;
          break;
        } else {
          if (hyou[(pq.second).first][(pq.second).second] == 0) {
            hyou[(pq.second).first][(pq.second).second] = -11;
          } else if (hyou[(pq.second).first][(pq.second).second] > 0) {
            hyou[(pq.second).first][(pq.second).second] =
                -hyou[(pq.second).first][(pq.second).second];
          }
        }
        que.push(pq);
      }
    }
    if (hantei) {
      break;
    }
  }
  for (int i = 0; i < 1010; i++) {
    for (int j = 0; j < 1010; j++) {
      if (hyou[i][j] == -11) {
        hyou[i][j] = 0;
      } else if (hyou[i][j] > -10 && hyou[i][j] < 0) {
        hyou[i][j] = -hyou[i][j];
      }
    }
  }
  return counter;
}

int main() {
  int h, w, n;
  cin >> h >> w >> n;
  char c;
  int sh, sw;
  int data[9][2];
  for (int i = 1; i <= h; i++) {
    for (int j = 1; j <= w; j++) {
      cin >> c;
      if (c == '.') {
        hyou[i][j] = 0;
      } else if (c == 'S') {
        hyou[i][j] = 0;
        sh = i;
        sw = j;
      } else if (c == 'X') {
        hyou[i][j] = -10;
      } else {
        int d = c - '0';
        hyou[i][j] = d;
        data[d - 1][0] = i;
        data[d - 1][1] = j;
      }
    }
  }
  int counter = 0;
  for (int i = 0; i < n; i++) {
    counter += search(sh, sw, i + 1);
    sh = data[i][0];
    sw = data[i][1];
  }
  cout << counter << endl;
  return 0;
}


#include <algorithm>
#include <cmath>
#include <complex>
#include <cstdio>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <utility>
#include <vector>
#define vi vector<int>
#define vvi vector<vector<int>>
#define ll long long int
#define vl vector<ll>
#define vvl vector<vector<ll>>
#define vb vector<bool>
#define vc vector<char>
#define vs vector<string>
#define ld long double
#define INF 1e9
#define EPS 0.0000000001
#define rep(i, n) for (int i = 0; i < n; i++)
#define CC puts("-------ok--------");
#define all(in) in.begin(), in.end()
#define bv vector<bool>
using namespace std;
typedef pair<int, int> pii;
#define MAX 99999999
vector<vector<char>> v(100, vc(100));
vector<pii> u(1000);
int mx[] = {0, 0, 1, -1};
int my[] = {1, -1, 0, 0};
int h, w, n;
int bfs(pii st, pii g) {
  queue<pii> que;
  vvi d(1000, vi(1000, INF));
  que.push(st);
  d[st.first][st.second] = 0;
  while (!que.empty()) {
    pii p = que.front();
    que.pop();
    if (p == g)
      break;
    rep(i, 4) {
      int ny = p.first + my[i];
      int nx = p.second + mx[i];
      pii np = pii(ny, nx);
      if (0 <= ny && ny < h && 0 <= nx && nx < w && d[ny][nx] == INF &&
          v[ny][nx] != 'X') {
        d[ny][nx] = d[p.first][p.second] + 1;
        que.push(np);
      }
    }
  }
  return d[g.first][g.second];
}
int main() {
  pii st;
  cin >> h >> w >> n;
  int ans = 0;
  rep(i, h) rep(j, w) {
    cin >> v[i][j];
    if (v[i][j] == 'S')
      st = pii(i, j);
    else if (v[i][j] != 'X' && v[i][j] != '.') {
      u[(v[i][j] - 48)] = pii(i, j);
      // cout<<v[i][j]-48<<endl;
    }
  }
  u[0] = st;
  for (int i = 0; i < n; i++) {
    ans += bfs(u[i], u[i + 1]);
  }
  cout << ans << endl;
}

#include <algorithm>
#include <cmath>
#include <complex>
#include <cstdio>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <utility>
#include <vector>
#define vi vector<int>
#define vvi vector<vector<int>>
#define ll long long int
#define vl vector<ll>
#define vvl vector<vector<ll>>
#define vb vector<bool>
#define vc vector<char>
#define vs vector<string>
#define ld long double
#define INF 1e9
#define EPS 0.0000000001
#define rep(i, n) for (int i = 0; i < n; i++)
#define CC puts("-------ok--------");
#define all(in) in.begin(), in.end()
#define bv vector<bool>
using namespace std;
typedef pair<int, int> pii;
#define MAX 99999999
vector<vector<char>> v(2000, vc(2000));
vector<pii> u(1000);
int mx[] = {0, 0, 1, -1};
int my[] = {1, -1, 0, 0};
int h, w, n;
int bfs(pii st, pii g) {
  queue<pii> que;
  vvi d(2000, vi(2000, INF));
  que.push(st);
  d[st.first][st.second] = 0;
  while (!que.empty()) {
    pii p = que.front();
    que.pop();
    if (p == g)
      break;
    rep(i, 4) {
      int ny = p.first + my[i];
      int nx = p.second + mx[i];
      pii np = pii(ny, nx);
      if (0 <= ny && ny < h && 0 <= nx && nx < w && d[ny][nx] == INF &&
          v[ny][nx] != 'X') {
        d[ny][nx] = d[p.first][p.second] + 1;
        que.push(np);
      }
    }
  }
  return d[g.first][g.second];
}
int main() {
  pii st;
  cin >> h >> w >> n;
  int ans = 0;
  rep(i, h) rep(j, w) {
    cin >> v[i][j];
    if (v[i][j] == 'S')
      st = pii(i, j);
    else if (v[i][j] != 'X' && v[i][j] != '.') {
      u[(v[i][j] - 48)] = pii(i, j);
      // cout<<v[i][j]-48<<endl;
    }
  }
  u[0] = st;
  for (int i = 0; i < n; i++) {
    ans += bfs(u[i], u[i + 1]);
  }
  cout << ans << endl;
}


// from : http://judge.u-aizu.ac.jp/onlinejudge/review.jsp?rid=1811250#1

#include <iostream>
#include <queue>
#include <vector>

using namespace std;

#define DEBUG(x) cout << (#x) << ": " << (x) << endl

int nowS = 0;
int x, y, n;
int mp[1000][1000] = {};
int k[4] = {1, -1, 0, 0};
int h[4] = {0, 0, 1, -1};
int cx[9] = {};
int cy[9] = {};
queue<int> bufX, bufY, bufD;

bool search(int xx, int yy, int dd) {
  bufX.pop();
  bufY.pop();
  bufD.pop();

  for (int i = 0; i < 4; i++) {
    int nx = xx + k[i];
    int ny = yy + h[i];
    if (nx < 0 || nx >= x || ny < 0 || ny >= y) //?????????
      continue;
    if (mp[ny][nx] == -1) { //?????
      continue;
    }
    if (cx[nowS] == nx && cy[nowS] == ny) { //??????
      nowS++;
      while (!bufX.empty()) {
        bufX.pop();
        bufY.pop();
        bufD.pop();
      }
      if (nowS == n) { //?????????????????????
        cout << dd + 1 << endl;
        return true;
      } else { //
        bufX.push(nx);
        bufY.push(ny);
        bufD.push(dd + 1);
        mp[ny][nx] = nowS + 1;
      }
      return false;
    }
    if (mp[ny][nx] >= 0 && mp[ny][nx] < nowS + 1) {
      bufX.push(nx);
      bufY.push(ny);
      bufD.push(dd + 1);
      mp[ny][nx] = nowS + 1;
    }
  }
  return false;
}

int main() {
  int ch = 0;
  cin >> y >> x >> n;
  for (int i = 0; i < y; i++) { //??\\???
    char c[1001];
    cin >> c;
    for (int j = 0; j < x; j++) {
      if (c[j] == 'X')
        mp[i][j] = -1;
      else if (c[j] == 'S') {
        bufX.push(j);
        bufY.push(i);
        bufD.push(0);
        mp[j][i] = 1;
      } else {
        mp[i][j] = 0;
      }
      if (c[j] >= 48 && c[j] <= 57) {
        int m;
        m = c[j] - 49;
        cx[m] = j;
        cy[m] = i;
        ch++;
      }
    }
  }

  while (!search(bufX.front(), bufY.front(), bufD.front())) {
  } //???????????????§?????????

  return 0;
}

// from : http://judge.u-aizu.ac.jp/onlinejudge/review.jsp?rid=1811250#1

#include <iostream>
#include <queue>
#include <vector>

using namespace std;

#define DEBUG(x) cout << (#x) << ": " << (x) << endl

int nowS = 0;
int x, y, n;
int mp[1000][1000] = {};
int k[4] = {1, -1, 0, 0};
int h[4] = {0, 0, 1, -1};
int cx[9] = {};
int cy[9] = {};
queue<int> bufX, bufY, bufD;

bool search(int xx, int yy, int dd) {
  bufX.pop();
  bufY.pop();
  bufD.pop();

  for (int i = 0; i < 4; i++) {
    int nx = xx + k[i];
    int ny = yy + h[i];
    if (nx < 0 || nx >= x || ny < 0 || ny >= y) //?????????
      continue;
    if (mp[ny][nx] == -1) { //?????
      continue;
    }
    if (cx[nowS] == nx && cy[nowS] == ny) { //??????
      nowS++;
      while (!bufX.empty()) {
        bufX.pop();
        bufY.pop();
        bufD.pop();
      }
      if (nowS == n) { //?????????????????????
        cout << dd + 1 << endl;
        return true;
      } else { //
        bufX.push(nx);
        bufY.push(ny);
        bufD.push(dd + 1);
        mp[ny][nx] = nowS + 1;
      }
      return false;
    }
    if (mp[ny][nx] >= 0 && mp[ny][nx] < nowS + 1) {
      bufX.push(nx);
      bufY.push(ny);
      bufD.push(dd + 1);
      mp[ny][nx] = nowS + 1;
    }
  }
  return false;
}

int main() {
  int ch = 0;
  cin >> y >> x >> n;
  for (int i = 0; i < y; i++) { //??\\???
    char c[1001];
    cin >> c;
    for (int j = 0; j < x; j++) {
      if (c[j] == 'X')
        mp[i][j] = -1;
      else if (c[j] == 'S') {
        bufX.push(j);
        bufY.push(i);
        bufD.push(0);
        mp[i][j] = 1;
      } else {
        mp[i][j] = 0;
      }
      if (c[j] >= 48 && c[j] <= 57) {
        int m;
        m = c[j] - 49;
        cx[m] = j;
        cy[m] = i;
        ch++;
      }
    }
  }

  while (!search(bufX.front(), bufY.front(), bufD.front())) {
  } //????????????????§?????????

  return 0;
}


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

char ma[1001][1001];
bool visited[1001][1001];
int h, w, n;
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, -1, 0, 1};
int sx, sy;
vector<pair<int, int>> vec(10);
queue<pair<pair<int, int>, int>> que;
int bfs(int d) {
  while (que.size()) {
    pair<pair<int, int>, int> q = que.front();
    que.pop();
    int x = q.first.first;
    int y = q.first.second;
    if (ma[y][x] - '0' == d) {
      return q.second;
    }
    visited[y][x] = 1;
    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 && ma[ny][nx] != 'X' &&
          !visited[ny][nx]) {
        que.push(make_pair(make_pair(nx, ny), q.second + 1));
      }
    }
  }
  return 0;
}

int main() {
  cin >> h >> w >> n;
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      cin >> ma[i][j];
      if (ma[i][j] > '0' && ma[i][j] <= '9') {
        vec[ma[i][j] - '0'] = make_pair(j, i);
      }
      if (ma[i][j] == 'S') {
        vec[0] = make_pair(j, i);
      }
    }
  }
  int c = 0;
  for (int i = 1; i <= n; i++) {
    while (que.size())
      que.pop();
    memset(visited, 0, sizeof(visited));
    que.push(make_pair(make_pair(vec[i - 1].first, vec[i - 1].second), 0));
    c += bfs(i);
  }
  cout << c << endl;
}

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

char ma[1001][1001];
bool visited[1001][1001];
int h, w, n;
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, -1, 0, 1};
int sx, sy;
vector<pair<int, int>> vec(10);
queue<pair<pair<int, int>, int>> que;
int bfs(int d) {
  while (que.size()) {
    pair<pair<int, int>, int> q = que.front();
    que.pop();
    int x = q.first.first;
    int y = q.first.second;
    if (visited[y][x])
      continue;
    if (ma[y][x] - '0' == d) {
      return q.second;
    }
    visited[y][x] = 1;
    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 && ma[ny][nx] != 'X' &&
          !visited[ny][nx]) {
        que.push(make_pair(make_pair(nx, ny), q.second + 1));
      }
    }
  }
  return 0;
}

int main() {
  cin >> h >> w >> n;
  for (int i = 0; i < h; i++) {
    string str;
    cin >> str;
    for (int j = 0; j < w; j++) {
      ma[i][j] = str[j];
      if (ma[i][j] > '0' && ma[i][j] <= '9') {
        vec[ma[i][j] - '0'] = make_pair(j, i);
      }
      if (ma[i][j] == 'S') {
        vec[0] = make_pair(j, i);
      }
    }
  }
  int c = 0;
  for (int i = 1; i <= n; i++) {
    while (que.size())
      que.pop();
    memset(visited, 0, sizeof(visited));
    que.push(make_pair(make_pair(vec[i - 1].first, vec[i - 1].second), 0));
    c += bfs(i);
  }
  cout << c << endl;
}


#include <cstring>
#include <iostream>
#include <queue>

using namespace std;

int mx[4] = {0, 0, 1, -1};
int my[4] = {1, -1, 0, 0};
char map[1000][1000];
char c = '1';

struct M {
  int x;
  int y;
  int cnt;
};

M s, v;

int run(int h, int w) {
  int came[1000][1000] = {0};
  queue<M> que;
  s.cnt = 0;
  que.push(s);
  while (1) {
    s = que.front();
    que.pop();
    came[s.y][s.x] = s.cnt;
    if (map[s.y][s.x] == c) {
      while (!que.empty())
        que.pop();
      c++;
      return s.cnt;
    }
    for (int i = 0; i < 4; i++) {
      if (s.x + mx[i] > -1 && s.x + mx[i] < w && s.y + my[i] > -1 &&
          s.y + my[i] < h) {
        v = s;
        v.x += mx[i];
        v.y += my[i];
        v.cnt++;
        if (map[v.y][v.x] != 'X' && came[v.y][v.x] == 0) {
          que.push(v);
        }
      }
    }
  }
}

int main() {
  s.x = -1;
  int h, w, n;
  cin >> h >> w >> n;
  for (int i = 0; i < h; i++) {
    cin >> map[i];
    for (int j = 0; j < w && s.x < 0; j++) {
      if (map[i][j] == 'S') {
        s.x = j;
        s.y = i;
        break;
      }
    }
  }
  int ans = 0;
  while (n) {
    n--;
    ans += run(h, w);
  }
  cout << ans << endl;
  return 0;
}

#include <cstring>
#include <iostream>
#include <queue>
using namespace std;
struct ST {
  int x;
  int y;
  int cnt = 0;
};
bool came[1000][1000] = {{0}};
char map[1000][1000];
int main() {
  ST m, s;
  queue<ST> que;
  int n;
  int w, h;
  int mx[4] = {0, 0, 1, -1};
  int my[4] = {1, -1, 0, 0};
  cin >> h >> w >> n;
  char c = '0';
  bool a = true;
  for (int i = 0; i < h; i++) {
    cin >> map[i];
    if (a) {
      for (int j = 0; j < w; j++ && a) {
        if (map[i][j] == 'S') {
          m.x = j;
          m.y = i;
          a = false;
        }
      }
    }
  }
  que.push(m);
  int cnt = 0;
  while (n) {
    n--;
    c++;
    while (!que.empty()) {
      m = que.front();
      que.pop();
      if (came[m.y][m.x] == 1)
        continue;
      came[m.y][m.x] = 1;
      if (map[m.y][m.x] == c) {
        while (!que.empty()) {
          que.pop();
        }
        break;
      }
      for (int i = 0; i < 4; i++) {
        if (m.x + mx[i] > -1 && m.x + mx[i] < w && m.y + my[i] > -1 &&
            m.y + my[i] < h) {
          s = m;
          s.x += mx[i];
          s.y += my[i];
          s.cnt++;
          if (map[s.y][s.x] != 'X' && came[s.y][s.x] == 0) {
            que.push(s);
          }
        }
      }
    }
    memset(came, 0, sizeof(came));
    que.push(m);
  }
  cout << m.cnt << endl;
  return 0;
}


#include <stdio.h>
#include <string.h>

#include <iostream>
#include <queue>

using namespace std;

#define y .first
#define x .second

pair<int, int> p, cpy;

char route[1000][1000];

int came[1000][1000];

bool check(pair<int, int> now, int h, int w);

#define size sizeof came

int mx[] = {1, 0, 0, -1};
int my[] = {0, 1, -1, 0};

int main() {
  int h, w, n;
  scanf("%d %d %d", &h, &w, &n);

  char end = '0' + n, cheese = '1';

  scanf("%c", &route[0][0]);

  int i, j;
  for (i = 0; i < h; ++i) {
    for (j = 0; j <= w; ++j) {
      scanf("%c", &route[i][j]);

      if (route[i][j] == 'S') {
        p y = i;
        p x = j;
      }
    }
  }

  int ans = 0;

  do {
    queue<pair<int, int>> que;

    memset(came, 0, size);

    while (route[p y][p x] != cheese) {
      int i;
      for (i = 0; i < 4; ++i) {
        cpy y = p y + my[i];
        cpy x = p x + mx[i];

        if (route[cpy y][cpy x] != 'X' && check(cpy, h, w) == true) {
          came[cpy y][cpy x] = came[p y][p x] + 1;

          que.push(cpy);
        }
      }

      came[p y][p x] = 1;

      p = que.front();

      que.pop();
    }

    ++cheese;

    ans += came[p y][p x];

  } while (cheese <= end);

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

  return 0;
}

bool check(pair<int, int> now, int h, int w) {
  if (now y >= h || now x >= w || now y < 0 || now x < 0)
    return false;

  else if (came[now y][now x] > 0)
    return false;

  return true;
}

#include <stdio.h>
#include <string.h>

#include <iostream>
#include <queue>

using namespace std;

#define y .first
#define x .second

pair<int, int> p, cpy;

char route[1000 + 1][1000 + 1];

int came[1000 + 1][1000 + 1];

bool check(pair<int, int> now, int h, int w);

#define size sizeof came

int mx[] = {1, 0, 0, -1};
int my[] = {0, 1, -1, 0};

int main() {
  int h, w, n;
  scanf("%d %d %d", &h, &w, &n);

  char end = '0' + n, cheese = '1';

  scanf("%c", &route[0][0]);

  int i, j;
  for (i = 0; i < h; ++i) {
    for (j = 0; j <= w; ++j) {
      scanf("%c", &route[i][j]);

      if (route[i][j] == 'S') {
        p y = i;
        p x = j;
      }
    }
  }

  int ans = 0;

  do {
    queue<pair<int, int>> que;

    memset(came, 0, size);

    while (route[p y][p x] != cheese) {
      int i;
      for (i = 0; i < 4; ++i) {
        cpy y = p y + my[i];
        cpy x = p x + mx[i];

        if (route[cpy y][cpy x] != 'X' && check(cpy, h, w) == true) {
          came[cpy y][cpy x] = came[p y][p x] + 1;

          que.push(cpy);
        }
      }

      came[p y][p x] = 1;

      p = que.front();

      que.pop();
    }

    ++cheese;

    ans += came[p y][p x];

  } while (cheese <= end);

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

  return 0;
}

bool check(pair<int, int> now, int h, int w) {
  if (now y >= h || now x >= w || now y < 0 || now x < 0)
    return false;

  else if (came[now y][now x] > 0)
    return false;

  return true;
}


#include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <iterator>
#include <map>
#include <queue>
#include <string>
#include <vector>
using namespace std;

int H, W, N;
int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};
char MAP[1000 + 1][1000 + 1];
int f[1000 + 1][1000 + 1];
int d[1000 + 1][1000 + 1];
int main() {
  cin >> H >> W >> N;
  queue<char> qux;
  queue<char> quy;
  vector<int> ans(N + 1);
  for (int i = 1; i < H + 1; ++i) {
    for (int j = 1; j < W + 1; ++j) {
      cin >> MAP[i][j];
      f[i][j] = 0;
      if (MAP[i][j] == 'S') {
        qux.push(i);
        quy.push(j);
        f[i][j] = 1;
        d[i][j] = 0;
      }
    }
  }
  int x;
  int y;
  for (int i = 1; i < N + 1; ++i) {
    while (1 /*qux.size()&&quy.size()*/) {
      x = qux.front();
      y = quy.front();
      // cout << x << " " << y << " " << d[x][y] << "\\n";
      qux.pop();
      quy.pop();
      // if('0'<=MAP[x][y]&&MAP[x][y]<='9'){
      // if(((int)MAP[x][y]-'0')==i) {
      if (atoi(&MAP[x][y]) == i) {
        ans[i] = d[x][y];
        for (int j = 1; j < H + 1; ++j) {
          for (int k = 1; k < W + 1; ++k) {
            f[i][j] = 0;
          }
        }
        d[x][y] = 0;
        break;
      }
      //}
      for (int j = 0; j < 4; ++j) {
        int nx = x + dx[j];
        int ny = y + dy[j];
        if (1 <= nx && nx <= H && 1 <= ny && ny <= W && MAP[nx][ny] != 'X' &&
            f[nx][ny] == 0) {
          qux.push(nx);
          quy.push(ny);
          f[nx][ny] = 1;
          d[nx][ny] = d[x][y] + 1;
        }
      }
    }
  }
  int ANS = 0;
  for (int i = 1; i < N + 1; ++i) {
    ANS += ans[i];
  }
  cout << ANS << "\\n";
  return 0;
}

#include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <iterator>
#include <map>
#include <queue>
#include <string>
#include <vector>
using namespace std;

int H, W, N;
int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};
char MAP[1000 + 1][1000 + 1];
int f[1000 + 1][1000 + 1];
int d[1000 + 1][1000 + 1];
int main() {
  cin >> H >> W >> N;
  vector<int> ans(N + 1);
  int startx, starty;
  for (int i = 1; i < H + 1; ++i) {
    for (int j = 1; j < W + 1; ++j) {
      cin >> MAP[i][j];
      f[i][j] = 0;
      if (MAP[i][j] == 'S') {
        startx = i, starty = j;
        // qux.push(i);
        // quy.push(j);
        f[i][j] = 1;
        d[i][j] = 0;
      }
    }
  }
  // cout << qux.size() << " " << quy.size() << "\\n";
  for (int i = 1; i < N + 1; ++i) {
    int x;
    int y;
    queue<int> qux;
    queue<int> quy;
    qux.push(startx);
    quy.push(starty);
    while (1) {
      if (!(qux.size() && quy.size())) {
        cout << x << " " << y << "\\n";
        break;
      }
      x = qux.front();
      y = quy.front();
      // cout << x << " " << y << " " << d[x][y] << "\\n";
      qux.pop();
      quy.pop();
      if (atoi(&MAP[x][y]) == i) {
        ans[i] = d[x][y];
        // cout << i << " " <<  d[x][y] << "\\n";
        for (int j = 1; j < H + 1; ++j) {
          for (int k = 1; k < W + 1; ++k) {
            f[j][k] = 0;
          }
        }
        startx = x;
        starty = y;
        d[x][y] = 0;
        break;
      }
      for (int j = 0; j < 4; ++j) {
        int nx = x + dx[j];
        int ny = y + dy[j];
        if (1 <= nx && nx <= H && 1 <= ny && ny <= W && MAP[nx][ny] != 'X' &&
            f[nx][ny] == 0) {
          // cout << "ok\\n";
          qux.push(nx);
          quy.push(ny);
          f[nx][ny] = 1;
          d[nx][ny] = d[x][y] + 1;
        }
      }
    }
  }
  int ANS = 0;
  for (int i = 1; i < N + 1; ++i) {
    ANS += ans[i];
  }
  cout << ANS << "\\n";
  return 0;
}


#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
using namespace std;
typedef long long ll;
typedef pair<ll, ll> P;
struct T {
  ll first, second, third;
};
typedef double db;
string c[1001];
const ll INF = 0xffffffffff;
P s[10], g[10];
ll vx[4] = {1, 0, -1, 0};
ll vy[4] = {0, 1, 0, -1};
ll n, h, w;
bool visited[1001][1001];

ll bfs(ll sx, ll sy, ll gx, ll gy) {
  queue<T> q;
  q.push((T){sx, sy, 0});
  while (1) {
    T t = q.front();
    q.pop();
    visited[t.second][t.first] = 1;
    if (t.first == gx && t.second == gy)
      return t.third;
    for (ll i = 0; i < 4; i++) {
      ll nx = t.first + vx[i];
      ll ny = t.second + vy[i];
      if (0 <= nx && nx < w && 0 <= ny && ny < h && c[ny][nx] == '.' &&
          !visited[ny][nx])
        q.push((T){nx, ny, t.third + 1});
    }
  }
}

int main() {
  scanf("%lld%lld%lld", &h, &w, &n);
  for (ll i = 0; i < h; i++)
    cin >> c[i];
  for (ll i = 0; i < h; i++)
    for (ll j = 0; j < w; j++) {
      if (c[i][j] == 'S') {
        s[0] = P(i, j); // y x
        c[i][j] = '.';
      }
      if ('1' <= c[i][j] && c[i][j] <= '9') {
        s[c[i][j] - '0'] = P(i, j);
        g[c[i][j] - '1'] = P(i, j);
        c[i][j] = '.';
      }
    }
  ll ans = 0;
  for (ll i = 0; i < n; i++) {
    fill(visited[0], visited[1000], 0);
    ans += bfs(s[i].second, s[i].first, g[i].second, g[i].first);
  }
  printf("%lld\\n", ans);
}

#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
using namespace std;
typedef long long ll;
typedef pair<ll, ll> P;
struct T {
  ll first, second, third;
};
typedef double db;
string c[1001];
const ll INF = 0xffffffffff;
P s[10], g[10];
ll vx[4] = {1, 0, -1, 0};
ll vy[4] = {0, 1, 0, -1};
ll n, h, w;
bool visited[1001][1001];

ll bfs(ll sx, ll sy, ll gx, ll gy) {
  queue<T> q;
  while (!q.empty())
    q.pop();
  q.push((T){sx, sy, 0});
  visited[sy][sx] = 1;
  while (1) {
    T t = q.front();
    q.pop();
    if (t.first == gx && t.second == gy)
      return t.third;
    for (ll i = 0; i < 4; i++) {
      ll nx = t.first + vx[i];
      ll ny = t.second + vy[i];
      if (0 <= nx && nx < w && 0 <= ny && ny < h && c[ny][nx] == '.' &&
          !visited[ny][nx]) {
        q.push((T){nx, ny, t.third + 1});
        visited[ny][nx] = 1;
      }
    }
  }
}

int main() {
  scanf("%lld%lld%lld", &h, &w, &n);
  for (ll i = 0; i < h; i++)
    cin >> c[i];
  for (ll i = 0; i < h; i++)
    for (ll j = 0; j < w; j++) {
      if (c[i][j] == 'S') {
        s[0] = P(i, j); // y x
        c[i][j] = '.';
      }
      if ('1' <= c[i][j] && c[i][j] <= '9') {
        s[c[i][j] - '0'] = P(i, j);
        g[c[i][j] - '0' - 1] = P(i, j);
        c[i][j] = '.';
      }
    }
  ll ans = 0;
  for (ll i = 0; i < n; i++) {
    fill(visited[0], visited[1000], 0);
    ans += bfs(s[i].second, s[i].first, g[i].second, g[i].first);
  }
  printf("%lld\\n", ans);
}


#include <algorithm>
#include <functional>
#include <iostream>
#include <queue>
#include <stack>
#include <string>
#include <vector>

using namespace std;

struct point {
  int x, y, step, vital;
};
const int dx[4] = {-1, 0, 0, 1};
const int dy[4] = {0, -1, 1, 0};

int H, W, N;

point search(const vector<vector<char>> &field, point start) {
  vector<vector<bool>> isVisited(H, vector<bool>(W));
  queue<point> Que;
  Que.push(start);
  isVisited[start.y][start.x] = true;
  while (!Que.empty()) {
    point p = Que.front();
    Que.pop();
    if (isVisited[p.y][p.x] != true && field[p.y][p.x] == p.vital + '0') {
      ++p.vital;
      return (p);
    }
    isVisited[p.y][p.x] = true;
    for (int i = 0; i < 4; ++i) {
      int nx = p.x + dx[i];
      int ny = p.y + dy[i];
      if (0 <= nx && nx < W && 0 <= ny && ny < H &&
          isVisited[ny][nx] == false && field[ny][nx] != 'X') {
        point np;
        np.x = nx;
        np.y = ny;
        np.step = p.step + 1;
        np.vital = p.vital;
        Que.push(np);
      }
    }
  }
}

void solve() {
  cin >> H >> W >> N;
  vector<vector<char>> field(H, vector<char>(W));
  point start;
  for (int i = 0; i < H; ++i) {
    for (int j = 0; j < W; ++j) {
      cin >> field[i][j];
      if (field[i][j] == 'S') {
        start.x = j;
        start.y = i;
        start.step = 0;
        start.vital = 1;
      }
    }
  }
  int sum = 0;
  while (start.vital < N + 1) {
    start = search(field, start);
    sum += start.step;
    start.step = 0;
  }
  cout << sum << endl;
}

int main() {
  solve();
  return (0);
}

#include <algorithm>
#include <functional>
#include <iostream>
#include <queue>
#include <stack>
#include <string>
#include <vector>

using namespace std;

struct point {
  int x, y, step, vital;
};
const int dx[4] = {-1, 0, 0, 1};
const int dy[4] = {0, -1, 1, 0};

int H, W, N;

point search(const vector<vector<char>> &field, point start) {
  vector<vector<bool>> isVisited(H, vector<bool>(W));
  queue<point> Que;
  Que.push(start);
  isVisited[start.y][start.x] = true;
  while (!Que.empty()) {
    point p = Que.front();
    Que.pop();
    if (field[p.y][p.x] - '0' == p.vital) {
      ++p.vital;
      return (p);
    }
    for (int i = 0; i < 4; ++i) {
      int nx = p.x + dx[i];
      int ny = p.y + dy[i];
      if (0 <= nx && nx < W && 0 <= ny && ny < H &&
          isVisited[ny][nx] == false && field[ny][nx] != 'X') {
        point np;
        np.x = nx;
        np.y = ny;
        np.step = p.step + 1;
        np.vital = p.vital;
        Que.push(np);
        isVisited[ny][nx] = true;
      }
    }
  }
}

void solve() {
  cin >> H >> W >> N;
  vector<vector<char>> field(H, vector<char>(W));
  point start;
  for (int i = 0; i < H; ++i) {
    for (int j = 0; j < W; ++j) {
      cin >> field[i][j];
      if (field[i][j] == 'S') {
        start.x = j;
        start.y = i;
        start.step = 0;
        start.vital = 1;
      }
    }
  }
  int sum = 0;
  while (start.vital < N + 1) {
    start = search(field, start);
    sum += start.step;
    start.step = 0;
  }
  cout << sum << endl;
}

int main() {
  solve();
  return (0);
}


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

void zero();

struct p {
  int x, y, cnt;
};
int H, W, N;
int tizu[1001][1001];
bool flag[1001][1001] = {false};
int main() {
  queue<p> que;
  char a;
  char h[10] = "123456789";
  cin >> H >> W >> N;
  for (int i = 0; i < H; i++) {
    for (int j = 0; j < W; j++) {
      cin >> a;
      if (a == 'S') {
        tizu[i][j] = 0;
        p temp;
        temp.x = j;
        temp.y = i;
        temp.cnt = 0;
        que.push(temp);
      } else if (a == 'X') {
        tizu[i][j] = -1;
      } else if (a == '.') {
        tizu[i][j] = 0;
      } else {
        for (int k = 0; k < 9; k++) {
          if (h[k] == a) {
            tizu[i][j] = k + 1;
          }
        }
      }
      // cout << tizu[i][j];
    }
    // cout << endl;
  }
  int max = 1;
  int step = 0;
  while (!que.empty()) {
    p temp = que.front();
    que.pop();
    if (tizu[temp.y][temp.x] == max) {
      max++;
      while (!que.empty())
        que.pop();
      if (max - 1 == N) {
        max = temp.cnt;
        break;
      }
      zero();
    }
    flag[temp.y][temp.x] = true;
    for (int i = 0; i < 4; i++) {
      int dx[4] = {1, -1, 0, 0};
      int dy[4] = {0, 0, 1, -1};
      int yy = temp.y + dy[i];
      int xx = temp.x + dx[i];
      if (flag[yy][xx] != true) {
        if (yy > -1 && xx > -1 && yy < H && xx < W && tizu[yy][xx] != -1) {
          p tt;
          tt.y = yy;
          tt.x = xx;
          tt.cnt = temp.cnt + 1;
          que.push(tt);
        }
      }
    }
  }
  cout << max << endl;
  return 0;
}
void zero() {
  for (int i = 0; i < H; i++) {
    for (int j = 0; j < W; j++) {
      flag[i][j] = false;
    }
  }
}

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

void zero();

struct p {
  int x, y, cnt;
};
int H, W, N;
int tizu[1001][1001];
bool flag[1001][1001] = {false};
int main() {
  queue<p> que;
  char a;
  char h[10] = "123456789";
  cin >> H >> W >> N;
  for (int i = 0; i < H; i++) {
    for (int j = 0; j < W; j++) {
      cin >> a;
      if (a == 'S') {
        tizu[i][j] = 0;
        p temp;
        temp.x = j;
        temp.y = i;
        temp.cnt = 0;
        que.push(temp);
      } else if (a == 'X') {
        tizu[i][j] = -1;
      } else if (a == '.') {
        tizu[i][j] = 0;
      } else {
        for (int k = 0; k < 9; k++) {
          if (h[k] == a) {
            tizu[i][j] = k + 1;
          }
        }
      }
      // cout << tizu[i][j];
    }
    // cout << endl;
  }
  int max = 1;
  int step = 0;
  zero();
  while (!que.empty()) {
    p temp = que.front();
    que.pop();
    if (tizu[temp.y][temp.x] == max) {
      max++;
      while (!que.empty())
        que.pop();
      if (max - 1 == N) {
        max = temp.cnt;
        break;
      }
      zero();
    }
    if (flag[temp.y][temp.x] == true)
      continue;
    flag[temp.y][temp.x] = true;
    for (int i = 0; i < 4; i++) {
      int dx[4] = {1, -1, 0, 0};
      int dy[4] = {0, 0, 1, -1};
      int yy = temp.y + dy[i];
      int xx = temp.x + dx[i];
      if (yy > -1 && xx > -1 && yy < H && xx < W && tizu[yy][xx] != -1 &&
          flag[yy][xx] == false) {
        p tt;
        tt.y = yy;
        tt.x = xx;
        tt.cnt = temp.cnt + 1;
        que.push(tt);
      }
    }
  }
  cout << max << endl;
  return 0;
}
void zero() {
  for (int i = 0; i < H; i++) {
    for (int j = 0; j < W; j++) {
      flag[i][j] = false;
    }
  }
}


#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
using namespace std;

int n, m, l, cnt, mx, my;
char a[1009][1009];
int vis[1009][1009];
pair<int, int> p[10], st;
int mov[4][2] = {1, 0, 0, -1, -1, 0, 0, 1};
struct status {
  int x, y;
  int ord;
  int fx;
  status(int a = 0, int b = 0, int c = 0, int s = 0) {
    x = a, y = b, ord = c, fx = s;
  }
  bool operator<(struct status t) const {
    if (ord != t.ord)
      return ord > t.ord;
    else
      return fx > t.fx;
  }
} tt[4];

void bfs(int x, int y, int color) {
  queue<struct status> q;
  struct status temp(x, y, 0,
                     fabs(x - p[color].first) + fabs(y - p[color].second));
  q.push(temp);
  int flag = 0;
  while (!q.empty()) {
    struct status nw = q.front();
    q.pop();
    if (nw.x == p[color].first && nw.y == p[color].second) {
      cnt += nw.ord;
      break;
    }
    vis[nw.x][nw.y] = 1;
    for (int i = 0; i < 4; i++) {
      int tx = mov[i][0] + nw.x, ty = nw.y + mov[i][1];
      if (tx >= 0 && tx < n && ty >= 0 && ty < m && !vis[tx][ty] &&
          a[tx][ty] != 'X') {
        struct status tmp(tx, ty, nw.ord + 1,
                          fabs(tx - p[color].first) +
                              fabs(ty - p[color].second));
        tt[i] = tmp;
        vis[tx][ty] = 1;
      }
    }
    sort(tt, tt + 4);
    for (int i = 0; i < 4; i++)
      q.push(tt[i]);
  }
}

int main() {
  while (~scanf("%d%d%d", &n, &m, &l)) {
    getchar();
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        scanf("%c", &a[i][j]);
        if (a[i][j] >= '0' && a[i][j] <= '9')
          p[a[i][j] - '0'].first = i, p[a[i][j] - '0'].second = j;
        if (a[i][j] == 'S')
          st.first = i, st.second = j;
      }
      getchar();
    }

    int sx = st.first, sy = st.second;
    cnt = 0;
    for (int i = 1; i <= l; i++) {
      memset(vis, 0, sizeof(vis));
      bfs(sx, sy, i);
      sx = p[i].first, sy = p[i].second;
    }
    printf("%d\\n", cnt);
  }
  return 0;
}

#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
using namespace std;

int n, m, l, cnt, mx, my;
char a[1009][1009];
int vis[1009][1009];
pair<int, int> p[10], st;
int mov[4][2] = {1, 0, 0, -1, -1, 0, 0, 1};
struct status {
  int x, y;
  int ord;
  int fx;
  status(int a = 0, int b = 0, int c = 0, int s = 0) {
    x = a, y = b, ord = c, fx = s;
  }
  bool operator<(struct status t) const {
    if (ord != t.ord)
      return ord > t.ord;
    else
      return fx > t.fx;
  }
} tt[4];

void bfs(int x, int y, int color) {
  queue<struct status> q;
  struct status temp(x, y, 0,
                     fabs(x - p[color].first) + fabs(y - p[color].second));
  q.push(temp);
  int flag = 0;
  while (!q.empty()) {
    struct status nw = q.front();
    q.pop();
    if (nw.x == p[color].first && nw.y == p[color].second) {
      cnt += nw.ord;
      break;
    }
    vis[nw.x][nw.y] = 1;
    int cct = 0;
    for (int i = 0; i < 4; i++) {
      int tx = mov[i][0] + nw.x, ty = nw.y + mov[i][1];
      if (tx >= 0 && tx < n && ty >= 0 && ty < m && !vis[tx][ty] &&
          a[tx][ty] != 'X') {
        struct status tmp(tx, ty, nw.ord + 1,
                          fabs(tx - p[color].first) +
                              fabs(ty - p[color].second));
        tt[cct++] = tmp;
        vis[tx][ty] = 1;
      }
    }
    sort(tt, tt + cct);
    for (int i = 0; i < cct; i++)
      q.push(tt[i]);
  }
}

int main() {
  while (~scanf("%d%d%d", &n, &m, &l)) {
    getchar();
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        scanf("%c", &a[i][j]);
        if (a[i][j] >= '0' && a[i][j] <= '9')
          p[a[i][j] - '0'].first = i, p[a[i][j] - '0'].second = j;
        if (a[i][j] == 'S')
          st.first = i, st.second = j;
      }
      getchar();
    }

    int sx = st.first, sy = st.second;
    cnt = 0;
    for (int i = 1; i <= l; i++) {
      memset(vis, 0, sizeof(vis));
      bfs(sx, sy, i);
      sx = p[i].first, sy = p[i].second;
    }
    printf("%d\\n", cnt);
  }
  return 0;
}


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

using namespace std;

#define rep(i, j) REP((i), 0, (j))
#define REP(i, j, k) for (int i = (j); (i) < (k); ++i)
#define BW(a, x, b) ((a) <= (x) && (x) <= (b))
#define ALL(v) (v).begin(), (v).end()
#define LENGTHOF(x) (sizeof(x) / sizeof(*(x)))
#define AFILL(a, b) fill((int *)a, (int *)(a + LENGTHOF(a)), b)
#define MP make_pair
#define PB push_back
#define F first
#define S second
#define INF 1 << 30
#define EPS 1e-10

typedef pair<int, int> pi;
typedef pair<pi, int> pii;
typedef pair<pi, pi> pipi;
typedef vector<int> vi;
typedef queue<int> qi;
typedef long long ll;

int H, W, N;
char g[1024][1024];
int dy[] = {0, -1, 0, 1}, dx[] = {-1, 0, 1, 0};

int main() {
  scanf("%d%d%d", &H, &W, &N);
  rep(i, H) scanf("%s", g[i]);

  int y, x;
  rep(i, H) rep(j, W) if (g[i][j] == 'S') y = i, x = j;

  queue<pipi> q;
  q.push(MP(MP(y, x), MP(1, 0))); // y, x, hp, time
  map<pii, int> m;
  m[MP(MP(y, x), 1)] = 1;

  while (!q.empty()) {
    pipi p = q.front();
    q.pop();

    int hp = p.S.F;
    if (g[p.F.F][p.F.S] - '0' == hp) {
      while (!q.empty())
        q.pop();
      hp++;
    }

    if (hp > N) {
      printf("%d\\n", p.S.S);
      break;
    }

    rep(d, 4) {
      int ny = p.F.F + dy[d], nx = p.F.S + dx[d];
      if (ny < 0 || ny >= H || nx < 0 || nx >= W || g[ny][nx] == 'X' ||
          m.find(MP(MP(ny, nx), hp)) != m.end())
        continue;
      q.push(MP(MP(ny, nx), MP(hp, p.S.S + 1)));
      m[MP(MP(ny, nx), hp)] = 1;
    }
  }
  return 0;
}

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

using namespace std;

#define rep(i, j) REP((i), 0, (j))
#define REP(i, j, k) for (int i = (j); (i) < (k); ++i)
#define BW(a, x, b) ((a) <= (x) && (x) <= (b))
#define ALL(v) (v).begin(), (v).end()
#define LENGTHOF(x) (sizeof(x) / sizeof(*(x)))
#define AFILL(a, b) fill((int *)a, (int *)(a + LENGTHOF(a)), b)
#define MP make_pair
#define PB push_back
#define F first
#define S second
#define INF 1 << 30
#define EPS 1e-10

typedef pair<int, int> pi;
typedef pair<pi, int> pii;
typedef pair<pi, pi> pipi;
typedef vector<int> vi;
typedef queue<int> qi;
typedef long long ll;

int H, W, N;
char g[1024][1024];
int dy[] = {0, -1, 0, 1}, dx[] = {-1, 0, 1, 0};

int main() {
  scanf("%d%d%d", &H, &W, &N);
  rep(i, H) scanf("%s", g[i]);

  int y, x;
  rep(i, H) rep(j, W) if (g[i][j] == 'S') y = i, x = j;

  queue<pipi> q;
  q.push(MP(MP(y, x), MP(1, 0))); // y, x, hp, time
  map<pi, int> m;
  m[MP(y, x)] = 1;

  while (!q.empty()) {
    pipi p = q.front();
    q.pop();

    int hp = p.S.F;
    if (g[p.F.F][p.F.S] - '0' == hp) {
      while (!q.empty())
        q.pop();
      m.clear();
      hp++;
    }

    if (hp > N) {
      printf("%d\\n", p.S.S);
      break;
    }

    rep(d, 4) {
      int ny = p.F.F + dy[d], nx = p.F.S + dx[d];
      if (ny < 0 || ny >= H || nx < 0 || nx >= W || g[ny][nx] == 'X' ||
          m.find(MP(ny, nx)) != m.end())
        continue;
      q.push(MP(MP(ny, nx), MP(hp, p.S.S + 1)));
      m[MP(ny, nx)] = 1;
    }
  }
  return 0;
}


#include <bits/stdc++.h>
#define PB push_back
#define MP make_pair
#define REP(i, n) for (int i = 0; i < (n); i++)
#define ALL(a) (a).begin(), (a).end()
#define INF 1000000001
#define MOD 100000
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> P;
const ull B = 100000007;
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, -1, 0, 1};
struct A {
  int x, y, cost;
};
int main() {
  int h, w, n, fin = -1;
  int x[11], y[11];
  memset(x, -1, sizeof(x));
  memset(y, -1, sizeof(y));
  cin >> h >> w >> n;
  char c;
  bool fld[1000][1000];
  REP(i, h) REP(j, w) {
    cin >> c;
    if (c == '.')
      fld[j][i] = true;
    else if (c == 'X')
      fld[j][i] = false;
    else if (c == 'S') {
      fld[j][i] = true;
      x[0] = j;
      y[0] = i;
    } else {
      fld[j][i] = true;
      x[c - '0'] = j;
      y[c - '0'] = i;
      fin = max(fin, c - '0');
    }
  }
  int ans = 0;
  REP(i, fin) {
    int d[1000][1000];
    memset(d, -1, sizeof(d));
    queue<A> Q;
    Q.push((A){x[i], y[i], 0});
    while (!Q.empty()) {
      A a = Q.front();
      Q.pop();
      int xx = a.x, yy = a.y, cost = a.cost;
      d[xx][yy] = cost;
      //                  cout<<xx<<" "<<yy<<endl;
      if (xx == x[i + 1] && yy == y[i + 1]) {
        ans += cost;
        break;
      }
      REP(j, 4) {
        int nx = xx + dx[j], ny = yy + dy[j];
        if (nx < 0 || nx >= w || ny < 0 || ny >= h || !fld[nx][ny])
          continue;
        if (d[nx][ny] != -1)
          continue;
        Q.push((A){nx, ny, cost + 1});
      }
    }
  }
  cout << ans << endl;
}

#include <bits/stdc++.h>
#define PB push_back
#define MP make_pair
#define REP(i, n) for (int i = 0; i < (n); i++)
#define ALL(a) (a).begin(), (a).end()
#define INF 1000000001
#define MOD 100000
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> P;
const ull B = 100000007;
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, -1, 0, 1};
struct A {
  int x, y, cost;
};
int main() {
  int h, w, n, fin = -1;
  int x[11], y[11];
  memset(x, -1, sizeof(x));
  memset(y, -1, sizeof(y));
  cin >> h >> w >> n;
  char c;
  bool fld[1000][1000];
  REP(i, h) REP(j, w) {
    cin >> c;
    if (c == '.')
      fld[j][i] = true;
    else if (c == 'X')
      fld[j][i] = false;
    else if (c == 'S') {
      fld[j][i] = true;
      x[0] = j;
      y[0] = i;
    } else {
      fld[j][i] = true;
      x[c - '0'] = j;
      y[c - '0'] = i;
      fin = max(fin, c - '0');
    }
  }
  int ans = 0;
  REP(i, fin) {
    int d[1000][1000];
    memset(d, -1, sizeof(d));
    queue<A> Q;
    Q.push((A){x[i], y[i], 0});
    while (!Q.empty()) {
      A a = Q.front();
      Q.pop();
      int xx = a.x, yy = a.y, cost = a.cost;
      //                  cout<<xx<<" "<<yy<<endl;
      if (d[xx][yy] != -1)
        continue;
      d[xx][yy] = cost;
      //                  cout<<xx<<" "<<yy<<" "<<cost<<endl;
      if (xx == x[i + 1] && yy == y[i + 1]) {
        ans += cost;
        break;
      }
      REP(j, 4) {
        int nx = xx + dx[j], ny = yy + dy[j];
        if (nx < 0 || nx >= w || ny < 0 || ny >= h || !fld[nx][ny])
          continue;
        Q.push((A){nx, ny, cost + 1});
      }
    }
  }
  cout << ans << endl;
}


#include <iostream>
#include <queue>
using namespace std;
struct Data {
  int x;
  int y;
  int t;
};
bool vis[1005][1005];
const int dx[] = {1, 0, -1, 0}, dy[] = {0, 1, 0, -1};
int main() {
  int h, w, n;
  cin >> h >> w >> n;
  string fi[1020];
  Data init;
  for (int i = 0; i < h; i++) {
    cin >> fi[i];
    for (int j = 0; j < w; j++) {
      if (fi[i][j] == 'S') {
        init.x = j;
        init.y = i;
      }
    }
  }
  init.t = 0;

  queue<Data> Q;
  Q.push(init);
  int now = 1;
  while (!Q.empty()) {
    Data D = Q.front();
    Q.pop();
    D.t++;
    vis[D.y][D.x] = true;
    if (fi[D.y][D.x] == now + '0') {
      now++;
      for (int i = 0; i < h; i++) {
        for (int j = 0; j < w; j++) {
          vis[i][j] = false;
        }
      }
      Q = queue<Data>();
      Q.push(D);
    }
    if (now == n + 1) {
      cout << D.t - 1 << endl;
      return 0;
    }
    for (int i = 0; i < 4; i++) {
      int x = D.x + dx[i];
      int y = D.y + dy[i];
      if (0 <= x && x < w && 0 <= y && y < h) {
        if (fi[y][x] == 'X')
          continue;
        if (vis[y][x])
          continue;
        Data E = D;
        E.x = x, E.y = y;
        Q.push(E);
      }
    }
  }
}

#include <iostream>
#include <queue>
using namespace std;
struct Data {
  int x;
  int y;
  int t;
};
bool vis[1005][1005];
const int dx[] = {1, 0, -1, 0}, dy[] = {0, 1, 0, -1};
int main() {
  int h, w, n;
  cin >> h >> w >> n;
  string fi[1020];
  Data init;
  for (int i = 0; i < h; i++) {
    cin >> fi[i];
    for (int j = 0; j < w; j++) {
      if (fi[i][j] == 'S') {
        init.x = j;
        init.y = i;
      }
    }
  }
  init.t = 0;

  queue<Data> Q;
  Q.push(init);
  int now = 1;
  while (!Q.empty()) {
    Data D = Q.front();
    Q.pop();
    D.t++;
    if (vis[D.y][D.x])
      continue;
    if (fi[D.y][D.x] == now + '0') {
      now++;
      for (int i = 0; i < h; i++) {
        for (int j = 0; j < w; j++) {
          vis[i][j] = false;
        }
      }
      Q = queue<Data>();
      Q.push(D);
    }
    vis[D.y][D.x] = true;
    if (now == n + 1) {
      cout << D.t - 1 << endl;
      return 0;
    }
    for (int i = 0; i < 4; i++) {
      int x = D.x + dx[i];
      int y = D.y + dy[i];
      if (0 <= x && x < w && 0 <= y && y < h) {
        if (fi[y][x] == 'X')
          continue;
        if (vis[y][x])
          continue;
        Data E = D;
        E.x = x, E.y = y;
        Q.push(E);
      }
    }
  }
}


#include <algorithm>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <math.h>
#include <queue>
#include <set>
#include <stack>
#include <string.h>
#include <string>

using namespace std;

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

typedef long long ll;
// 各地点の行と列をPairで持たせる
typedef pair<int, int> P;
int y, x, n, nx, ny, nextx, nexty;
int ans = 0;
int counter = 0;
int d[1000][1000] = {0};
char c[1100][1100];
int d1[] = {0, 0, -1, 1};
int d2[] = {1, -1, 0, 0};
int dc = 0;

int main() {
  cin >> y >> x >> n;
  queue<P> que;
  REP(i, y) { cin >> c[i]; }
  REP(i, y) {
    bool isFoundStart = false;
    REP(j, x) {
      if (c[i][j] == 'S') {
        isFoundStart = true;
        que.push(P(i, j));
        d[i][j] = 0;
        break;
      }
    }
    if (isFoundStart)
      break;
  }

  while (counter < n) {
    int memo[1100][1100] = {0};
    while (que.size()) {
      P p = que.front();
      que.pop();
      ny = p.first;
      nx = p.second;
      dc = d[ny][nx];

      if (c[ny][nx] - '0' == counter + 1) {
        counter++;

        if (counter == n) {
          cout << dc << endl;
          return 0;
        }
        queue<P> empty;
        swap(que, empty);
        que.push(P(ny, nx));
        c[ny][nx] = '.';

        break;
      }

      REP(i, 4) {
        nextx = nx + d1[i];
        nexty = ny + d2[i];

        if (nexty < 0 || nexty >= y || nextx < 0 || nextx >= x)
          continue;
        if (c[nexty][nextx] == 'X' || memo[nexty][nextx] != 0)
          continue;

        que.push(P(nexty, nextx));

        d[nexty][nextx] = dc + 1;
      }
      memo[ny][nx] = 1;
    }
  }
}

#include <algorithm>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <math.h>
#include <queue>
#include <set>
#include <stack>
#include <string.h>
#include <string>

using namespace std;

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

typedef long long ll;
// 各地点の行と列をPairで持たせる
typedef pair<int, int> P;
int y, x, n, nx, ny, nextx, nexty;
int ans = 0;
int counter = 0;
int d[1100][1100];
char c[1100][1100];
int d1[] = {0, 0, -1, 1};
int d2[] = {1, -1, 0, 0};
int dc = 0;
char key[] = "S123456789";
P st[10];

int bfs(P, P);

int main() {
  cin >> y >> x >> n;
  REP(i, y) { cin >> c[i]; }
  REP(i, y) {
    REP(j, x) {
      REP(k, n + 1) {
        if (c[i][j] == key[k])
          st[k] = P(i, j);
      }
    }
  }

  REP(i, n) {
    memset(d, -1, sizeof(d));

    ans += bfs(st[i], st[i + 1]);
  }
  cout << ans << endl;
  return 0;
}

int bfs(P s, P g) {
  queue<P> que;
  que.push(s);
  d[s.first][s.second] = 0;
  while (que.size()) {
    P p = que.front();
    que.pop();
    ny = p.first;
    nx = p.second;
    dc = d[ny][nx];

    if (p == g)
      break;

    REP(i, 4) {
      nextx = nx + d1[i];
      nexty = ny + d2[i];

      if (nexty < 0 || nexty >= y || nextx < 0 || nextx >= x)
        continue;

      if (c[nexty][nextx] == 'X' || d[nexty][nextx] != -1)
        continue;

      que.push(P(nexty, nextx));

      d[nexty][nextx] = dc + 1;
    }
  }
  return d[g.first][g.second];
}


#include "bits/stdc++.h"
#define MOD 1000000007
#define INF 11234567890
#define in std::cin
#define out std::cout
#define rep(i, N) for (LL i = 0; i < N; ++i)
typedef long long int LL;
typedef std::pair<LL, LL> P;
struct edge {
  LL to, cost;
};

LL H, W, N;
std::string field[1123];
LL Sx, Sy, xy[11];
LL ans;

LL d[1123456];
std::vector<edge> G[1123456];
void dijkstra(LL s) {
  std::priority_queue<P, std::vector<P>, std::greater<P>> que;
  std::fill(d, d + H * W + 1, INF);
  d[s] = 0;
  que.push(P(0, s));
  while (!que.empty()) {
    P p = que.top();
    que.pop();
    LL v = p.second;
    if (d[v] < p.first) {
      continue;
    }
    rep(i, G[v].size()) {
      edge e = G[v][i];
      if (d[e.to] > d[v] + e.cost) {
        d[e.to] = d[v] + e.cost;
        que.push(P(d[e.to], e.to));
      }
    }
  }
}

int main() {
  in >> H >> W >> N;
  rep(i, H) { in >> field[i]; }

  rep(x, H) {
    rep(y, W) {
      if (field[x][y] == 'X') {
        continue;
      }
      if (field[x][y] == 'S') {
        Sx = x;
        Sy = y;
      }
      if (field[x][y] != '.') {
        xy[field[x][y] - '0'] = x * W + y;
      }
      if (x < H - 1) {
        if (field[x + 1][y] != 'X') {
          G[x * W + y].push_back({(x + 1) * W + y, 1});
          G[(x + 1) * W + y].push_back({x * W + y, 1});
        }
      }
      if (y < W - 1) {
        if (field[x][y + 1] != 'X') {
          G[x * W + y].push_back({x * W + (y + 1), 1});
          G[x * W + (y + 1)].push_back({x * W + y, 1});
        }
      }
    }
  }
  dijkstra(Sx * W + Sy);
  rep(i, N) {
    ans += d[xy[i + 1]];
    dijkstra(xy[i + 1]);
  }

  out << ans << std::endl;
  return 0;
}

#include "bits/stdc++.h"
#define MOD 1000000007
#define INF 11234567890
#define in std::cin
#define out std::cout
#define rep(i, N) for (LL i = 0; i < N; ++i)
typedef long long int LL;
typedef std::pair<LL, LL> P;
struct edge {
  LL to, cost;
};

int H, W, N;
std::string field[1123];
int Sx, Sy, xy[11];
int ans;

LL d[1123456];
std::vector<edge> G[1123456];
void dijkstra(LL s) {
  std::priority_queue<P, std::vector<P>, std::greater<P>> que;
  std::fill(d, d + H * W + 1, INF);
  d[s] = 0;
  que.push(P(0, s));
  while (!que.empty()) {
    P p = que.top();
    que.pop();
    LL v = p.second;
    if (d[v] < p.first) {
      continue;
    }
    rep(i, G[v].size()) {
      edge e = G[v][i];
      if (d[e.to] > d[v] + e.cost) {
        d[e.to] = d[v] + e.cost;
        que.push(P(d[e.to], e.to));
      }
    }
  }
}

int main() {
  in >> H >> W >> N;
  rep(i, H) { in >> field[i]; }

  rep(x, H) {
    rep(y, W) {
      if (field[x][y] == 'X') {
        continue;
      }
      if (field[x][y] == 'S') {
        Sx = x;
        Sy = y;
      } else if (field[x][y] != '.') {
        xy[field[x][y] - '0'] = x * W + y;
      }
      if (x < H - 1) {
        if (field[x + 1][y] != 'X') {
          G[x * W + y].push_back({(x + 1) * W + y, 1});
          G[(x + 1) * W + y].push_back({x * W + y, 1});
        }
      }
      if (y < W - 1) {
        if (field[x][y + 1] != 'X') {
          G[x * W + y].push_back({x * W + (y + 1), 1});
          G[x * W + (y + 1)].push_back({x * W + y, 1});
        }
      }
    }
  }
  dijkstra(Sx * W + Sy);
  rep(i, N) {
    ans += d[xy[i + 1]];
    dijkstra(xy[i + 1]);
  }

  out << ans << std::endl;
  return 0;
}


#include "bits/stdc++.h"
#define MOD 1000000007
#define INF 11234567890
#define in std::cin
#define out std::cout
#define rep(i, N) for (LL i = 0; i < N; ++i)
typedef long long int LL;
typedef std::pair<LL, LL> P;
struct edge {
  LL to, cost;
};

int H, W, N;
std::string field[1123];
int Sx, Sy, x[11], y[11], ans;

int d[1123][1123];
int dx[] = {1, 0, -1, 0}, dy[] = {0, 1, 0, -1};
void bfs(LL sx, LL sy, LL gx, LL gy) {
  std::queue<P> que;
  memset(d, -1, sizeof(d));
  que.push({sx, sy});
  d[sx][sy] = 0;
  while (que.size() > 0) {
    auto pos = que.front();
    que.pop();
    if (pos.first == gx && pos.second == gy) {
      break;
    }
    rep(i, 4) {
      auto toX = pos.first + dx[i], toY = pos.second + dy[i];
      if (0 <= toX && toX < H && 0 <= toY && toY < W) {
        if (field[toX][toY] != 'X' && d[toX][toY] == -1) {
          que.push({toX, toY});
          d[toX][toY] = d[pos.first][pos.second] + 1;
        }
      }
    }
  }
}

int main() {
  in >> H >> W >> N;
  rep(i, H) { in >> field[i]; }

  rep(i, H) {
    rep(j, W) {
      if (field[i][j] == 'S') {
        Sx = i;
        Sy = j;
      } else if (field[i][j] != '.') {
        x[field[i][j] - '0'] = i;
        y[field[i][j] - '0'] = j;
      }
    }
  }
  x[0] = Sx;
  y[0] = Sy;
  rep(i, N) {
    bfs(x[i], y[i], x[i + 1], y[i + 1]);
    ans += d[x[i + 1]][y[i + 1]];
  }
  out << ans << std::endl;
  return 0;
}

#include "bits/stdc++.h"
#define MOD 1000000007
#define INF 11234567890
#define in std::cin
#define out std::cout
#define rep(i, N) for (LL i = 0; i < N; ++i)
typedef long long int LL;
typedef std::pair<LL, LL> P;
struct edge {
  LL to, cost;
};

int H, W, N;
std::string field[1123];
int Sx, Sy, x[11], y[11], ans;

int d[1123][1123];
int dx[] = {1, 0, -1, 0}, dy[] = {0, 1, 0, -1};
void bfs(LL sx, LL sy, LL gx, LL gy) {
  std::queue<P> que;
  memset(d, -1, sizeof(d));
  que.push({sx, sy});
  d[sx][sy] = 0;
  while (que.size() > 0) {
    auto pos = que.front();
    que.pop();
    if (pos.first == gx && pos.second == gy) {
      break;
    }
    rep(i, 4) {
      auto toX = pos.first + dx[i], toY = pos.second + dy[i];
      if (0 <= toX && toX < H && 0 <= toY && toY < W) {
        if (field[toX][toY] != 'X' && d[toX][toY] == -1) {
          que.push({toX, toY});
          d[toX][toY] = d[pos.first][pos.second] + 1;
        }
      }
    }
  }
}

int main() {
  in >> H >> W >> N;
  rep(i, H) { in >> field[i]; }

  rep(i, H) {
    rep(j, W) {
      if (field[i][j] == 'X') {
        continue;
      }
      if (field[i][j] == 'S') {
        Sx = i;
        Sy = j;
      } else if (field[i][j] != '.') {
        x[field[i][j] - '0'] = i;
        y[field[i][j] - '0'] = j;
      }
    }
  }
  x[0] = Sx;
  y[0] = Sy;
  rep(i, N) {
    bfs(x[i], y[i], x[i + 1], y[i + 1]);
    ans += d[x[i + 1]][y[i + 1]];
  }
  out << ans << std::endl;
  return 0;
}


#include <iostream>

typedef std::pair<int, int> P;

int h, w, PX[4] = {1, -1, 0, 0}, PY[4] = {0, 0, 1, -1};
char ch[100][100];
int sum = -1;

void dfs(P p) {
  ch[p.first][p.second] = ',';
  for (int i = 0; i < 4; ++i) {
    if (p.first + PY[i] >= 0 && h > p.first + PY[i] && w > p.second + PX[i] &&
        p.second + PX[i] >= 0) {
      if (ch[p.first][p.second] == ch[p.first + PY[i]][p.second + PX[i]]) {
        dfs(P(p.first + PY[i], p.second + PX[i]));
      }
    }
  }
}

void solve() {
  for (int i = 0; i < h; ++i) {
    for (int j = 0; j < w; ++j) {
      if (ch[i][j] != ',') {
        ++sum;
        dfs(P(i, j));
      }
    }
  }
}

int main() {
  while (1) {
    std::cin >> h >> w;
    if (h == 0 && w == 0)
      break;
    for (int i = 0; i < h; ++i) {
      for (int j = 0; j < w; ++j) {
        std::cin >> ch[i][j];
      }
    }
    solve();
    std::cout << sum << std::endl;
  }
  return 0;
}

#include <cctype>
#include <iostream>
#include <queue>
typedef std::pair<int, int> P;

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

int dx[4] = {1, -1, 0, 0}, dy[4] = {0, 0, 1, -1};
int h, w, n;
int d[MAX_H][MAX_W];
char ch[MAX_H][MAX_W];
P p[MAX_N + 1];

int bfs(P s, P g) {
  for (int i = 0; i < h; ++i) {
    for (int j = 0; j < w; ++j)
      d[i][j] = INF;
  }
  std::queue<P> que;
  que.push(s);
  d[s.second][s.first] = 0;
  while (!que.empty()) {
    P x = que.front();
    que.pop();
    if (x == g)
      break;
    for (int i = 0; i < 4; ++i) {
      int nx = x.first + dx[i];
      int ny = x.second + dy[i];
      if (nx >= 0 && ny >= 0 && nx < w && ny < h && d[ny][nx] == INF &&
          ch[ny][nx] != 'X') {
        que.push(P(nx, ny));
        d[ny][nx] = d[x.second][x.first] + 1;
      }
    }
  }
  return d[g.second][g.first];
}

int solve() {
  int res = 0;
  for (int i = 1; i <= n; ++i) {
    res += bfs(p[i - 1], p[i]);
  }
  return res;
}

int main() {
  std::cin >> h >> w >> n;
  for (int i = 0; i < h; ++i) {
    for (int j = 0; j < w; ++j) {
      std::cin >> ch[i][j];
      if (std::isdigit(ch[i][j])) {
        p[atoi(&ch[i][j])].first = j;
        p[atoi(&ch[i][j])].second = i;
      } else if (ch[i][j] == 'S') {
        p[0].first = j;
        p[0].second = i;
      }
    }
  }
  std::cout << solve() << std::endl;
  return 0;
}