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

int H, W, N;
char field[1000][1000];
int d[1000][1000];
pair<int, int> start;
pair<int, int> cheese;
int INF = 1000000;
int result = 0;

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

void bfs() {
  for (int n = 1; n < N + 1; n++) {
    queue<pair<int, int>> que;
    for (int i = 0; i < H; i++) {
      for (int j = 0; j < W; j++) {
        d[i][j] = INF;
      }
    }
    que.push(start);
    d[start.first][start.second] = 0;

    while (que.size()) {
      pair<int, int> p = que.front();
      que.pop();
      if (field[p.first][p.second] == '0' + (char)n) {
        cheese = p;
        break;
      }

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

        if (0 <= nx && nx <= H && 0 <= ny && ny <= W && field[nx][ny] != 'X' &&
            d[nx][ny] == INF) {
          que.push(pair<int, int>(nx, ny));
          d[nx][ny] = d[p.first][p.second] + 1;
        }
      }
    }
    result += d[cheese.first][cheese.second];
    start = cheese;
  }
}

int main() {
  scanf(" %d %d %d", &H, &W, &N);
  for (int i = 0; i < H; i++) {
    for (int j = 0; j < W; j++) {
      scanf(" %c", &field[i][j]);
      if (field[i][j] == 'S') {
        start.first = i;
        start.second = j;
      }
    }
  }
  bfs();
  printf("%d\\n", result);
}

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

int H, W, N;
char field[1000][1000];
int d[1000][1000];
pair<int, int> start;
pair<int, int> cheese;
int INF = 1000000;
int result = 0;

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

void bfs() {
  for (int n = 1; n < N + 1; n++) {
    queue<pair<int, int>> que;
    for (int i = 0; i < H; i++) {
      for (int j = 0; j < W; j++) {
        d[i][j] = INF;
      }
    }
    que.push(start);
    d[start.first][start.second] = 0;

    while (que.size()) {
      pair<int, int> p = que.front();
      que.pop();
      if (field[p.first][p.second] == '0' + (char)n) {
        cheese = p;
        break;
      }

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

        if (0 <= nx && nx < H && 0 <= ny && ny < W && field[nx][ny] != 'X' &&
            d[nx][ny] == INF) {
          que.push(pair<int, int>(nx, ny));
          d[nx][ny] = d[p.first][p.second] + 1;
        }
      }
    }
    result += d[cheese.first][cheese.second];
    start = cheese;
  }
}

int main() {
  scanf(" %d %d %d", &H, &W, &N);
  for (int i = 0; i < H; i++) {
    for (int j = 0; j < W; j++) {
      scanf(" %c", &field[i][j]);
      if (field[i][j] == 'S') {
        start.first = i;
        start.second = j;
      }
    }
  }
  bfs();
  printf("%d\\n", result);
}


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

using namespace std;

#define INF (1 << 26)

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

int main() {
  int H, W, N;

  cin >> H >> W >> N;

  vector<string> D(H);

  for (int i = 0; i < H; i++)
    cin >> D[i];

  int route = 0;

  for (int i = 1; i <= N; i++) {
    queue<pair<int, int>> que;

    vector<vector<int>> memo(H, vector<int>(W, INF));

    char start;

    if (i == 1) {
      start = 'S';
    } else {
      start = i + 48;
    }

    pair<int, int> start_;

    for (int i = 0; i < H; i++) {
      for (int j = 0; j < W; j++) {
        if (D[i][j] == start) {
          start_.first = j;
          start_.second = i;
        }
      }
    }

    que.push(start_);

    memo[start_.second][start_.first] = route;

    while (que.size()) {
      pair<int, int> place = que.front();
      que.pop();

      int x, y;

      x = place.first;
      y = place.second;

      for (int dir = 0; dir < 4; dir++) {
        if (0 <= x + dx[dir] && x + dx[dir] < W && 0 <= y + dy[dir] &&
            y + dy[dir] < H) {
          if (D[y][x] != 'X') {
            place.first = x + dx[dir];
            place.second = y + dy[dir];

            que.push(place);

            memo[y + dy[dir]][x + dx[dir]] = memo[y][x] + 1;

            if (D[y + dy[dir]][x + dx[dir]] - 48 == i) {
              route += memo[y][x] + 1;

              goto Exit;
            }
          }
        }
      }
    }

  Exit:;
  }

  cout << route << endl;

  return 0;
}

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

using namespace std;

#define INF (1 << 26)

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

int main() {
  int H, W, N;

  cin >> H >> W >> N;

  vector<string> D(H);

  for (int i = 0; i < H; i++)
    cin >> D[i];

  int route = 0;

  for (int i = 1; i <= N; i++) {
    queue<pair<int, int>> que;

    vector<vector<int>> memo(H, vector<int>(W, INF));

    char start;

    if (i == 1) {
      start = 'S';
    } else {
      start = i + 47;
    }

    pair<int, int> start_;

    for (int j = 0; j < H; j++) {
      for (int k = 0; k < W; k++) {
        if (D[j][k] == start) {
          start_.first = k;
          start_.second = j;
        }
      }
    }

    que.push(start_);

    memo[start_.second][start_.first] = route;

    while (que.size()) {
      pair<int, int> place = que.front();
      que.pop();

      int x, y;

      x = place.first;
      y = place.second;

      for (int dir = 0; dir < 4; dir++) {
        if (0 <= x + dx[dir] && x + dx[dir] < W && 0 <= y + dy[dir] &&
            y + dy[dir] < H) {
          if (D[y + dy[dir]][x + dx[dir]] != 'X' &&
              memo[y + dy[dir]][x + dx[dir]] == INF) {
            place.first = x + dx[dir];
            place.second = y + dy[dir];

            que.push(place);

            memo[y + dy[dir]][x + dx[dir]] = memo[y][x] + 1;

            if (D[y + dy[dir]][x + dx[dir]] - 48 == i) {
              route = memo[y][x] + 1;

              goto Exit;
            }
          }
        }
      }
    }

  Exit:;
  }

  cout << route << endl;

  return 0;
}


#include <algorithm>
#include <cstring>
#include <iostream>
#include <math.h>
#include <queue>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
using namespace std;
#define INF 100000
char map[1001][1001];
int h, w, n;
int d1[4] = {0, 1, 0, -1};
int d2[4] = {1, 0, -1, 0};
int i, j, x[10], y[10];
int bfs(int num) {
  int gy = y[num + 1], gx = x[num + 1];
  int d[1001][1001];
  for (int i = 0; i <= 1001; i++) {
    for (int j = 0; j <= 1001; j++) {
      d[i][j] = INF;
    }
  }
  queue<int> qx;
  queue<int> qy;
  qx.push(x[num]);
  qy.push(y[num]);
  d[y[num]][x[num]] = 0;
  while (qx.size() + qy.size() != 0) {
    int ny, nx;
    ny = qy.front();
    qy.pop();
    nx = qx.front();
    qx.pop();
    if (ny == gy && nx == gx) {
      break;
    }
    for (int i = 0; i < 4; i++) {
      int mx = nx + d1[i], my = ny + d2[i];
      if (0 <= mx && mx < w && 0 <= my && my < h && map[my][mx] != 'X' &&
          d[my][mx] == INF) {
        d[my][mx] = d[ny][nx] + 1;
        qx.push(mx);
        qy.push(my);
      }
    }
  }
  return d[gy][gx];
}
int main() {
  int ans = 0;
  cin >> h >> w >> n;
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      cin >> map[i][j];
      if (map[i][j] == 'S') {
        y[0] = i;
        x[0] = j;
      } else if ('0' < map[i][j] && map[i][j] <= '9') {
        y[(int)(map[i][j] - '0')] = i;
        x[(int)(map[i][j] - '0')] = j;
      }
    }
  }

  for (int i = 0; i < n; i++) {
    ans += bfs(i);
  }

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

#include <algorithm>
#include <cstring>
#include <iostream>
#include <math.h>
#include <queue>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
using namespace std;
#define INF 100000
char map[1001][1001];
int h, w, n;
int d1[4] = {0, 1, 0, -1};
int d2[4] = {1, 0, -1, 0};
int i, j, x[10], y[10];
int bfs(int num) {
  int gy = y[num + 1], gx = x[num + 1];
  int d[1001][1001];
  for (int i = 0; i < 1001; i++) {
    for (int j = 0; j < 1001; j++) {
      d[i][j] = INF;
    }
  }
  queue<int> qx;
  queue<int> qy;
  qx.push(x[num]);
  qy.push(y[num]);
  d[y[num]][x[num]] = 0;
  while (qx.size() + qy.size() != 0) {
    int ny, nx;
    ny = qy.front();
    qy.pop();
    nx = qx.front();
    qx.pop();
    if (ny == gy && nx == gx) {
      break;
    }
    for (int i = 0; i < 4; i++) {
      int mx = nx + d1[i], my = ny + d2[i];
      if (0 <= mx && mx < w && 0 <= my && my < h && map[my][mx] != 'X' &&
          d[my][mx] == INF) {
        d[my][mx] = d[ny][nx] + 1;
        qx.push(mx);
        qy.push(my);
      }
    }
  }
  return d[gy][gx];
}
int main() {
  int ans = 0;
  cin >> h >> w >> n;
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      cin >> map[i][j];
      if (map[i][j] == 'S') {
        y[0] = i;
        x[0] = j;
      } else if ('0' < map[i][j] && map[i][j] <= '9') {
        y[(int)(map[i][j] - '0')] = i;
        x[(int)(map[i][j] - '0')] = j;
      }
    }
  }

  for (int i = 0; i < n; i++) {
    ans += bfs(i);
  }

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

*** stack smashing detected ***: terminated


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

using namespace std;

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

int H, W, N;
char field[MAX_H][MAX_W];
int d[MAX_H][MAX_W]; // ?????????????????\\??´?????§??????????????°,
                     // 1~N??§?????????????????§????????°??????+1
int step[MAX_N + 1]; // ?????????????????\\??´?????§??????????????°,
                     // 1~N??§?????????????????§????????°??????+1
int sx, sy, gx, gy;
int power = 1; // ??????????????????
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};

typedef pair<int, int> P;

void reset_d() {
  for (int i = 0; i < H; i++)
    for (int j = 0; j < W; j++)
      d[i][j] = INF;
}

int bfs(int sx, int sy, int c) {
  queue<P> que;
  reset_d();
  d[sx][sy] = c;
  que.push(P(sx, sy));
  while (que.size()) {
    P p = que.front();
    que.pop();
    if (field[p.first][p.second] - '0' == N && step[N] != 0)
      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 && field[nx][ny] != 'X' &&
          d[nx][ny] == INF) {
        d[nx][ny] = d[p.first][p.second] + 1;
        que.push(P(nx, ny));
        if (field[nx][ny] - '0' == power) {
          step[power] = d[nx][ny];
          power++;
          return bfs(nx, ny, d[nx][ny]);
        }
      }
    }
  }
  return step[N];
}

void solve(int sx, int sy) {
  int res = bfs(sx, sy, 0);
  printf("%d\\n", res);
}

int main() {
  scanf("%d %d %d", &H, &W, &N);
  for (int i = 0; i < H; i++) {
    scanf("%s", field[i]);
  }
  for (int i = 0; i < H; i++) {
    for (int j = 0; j < W; j++) {
      if (field[i][j] == 'S') {
        sx = i;
        sy = j;
      }
      if (field[i][j] == 'G') {
        gx = i;
        gy = j;
      }
    }
  }
  solve(sx, sy);
  return 0;
}

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

using namespace std;

const int INF = -1;
const int MAX_H = 1010;
const int MAX_W = 1010;
const int MAX_N = 10;

int H, W, N;
char field[MAX_H][MAX_W];
int d[MAX_H][MAX_W];
int sx, sy, gx, gy;
int power = 1;
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};

typedef pair<int, int> P;

void reset_d() {
  for (int i = 0; i < H; i++)
    for (int j = 0; j < W; j++)
      d[i][j] = INF;
}

int bfs(int c) {
  queue<P> que;
  reset_d();
  d[sx][sy] = c;
  que.push(P(sx, sy));
  while (que.size()) {
    P p = que.front();
    que.pop();
    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 && field[nx][ny] != 'X' &&
          d[nx][ny] == INF) {
        d[nx][ny] = d[p.first][p.second] + 1;
        que.push(P(nx, ny));
        if (field[nx][ny] - '0' == power) {
          sx = nx;
          sy = ny;
          power++;
          return d[nx][ny];
        }
      }
    }
  }
  return INF;
}

void solve() {
  int c = 0;
  for (int i = 0; i < N; i++) {
    c = bfs(c);
  }
  printf("%d\\n", c);
}

int main() {
  scanf("%d %d %d", &H, &W, &N);
  for (int i = 0; i < H; i++) {
    scanf("%s", field[i]);
  }
  for (int i = 0; i < H; i++) {
    for (int j = 0; j < W; j++) {
      if (field[i][j] == 'S') {
        sx = i;
        sy = j;
      }
      if (field[i][j] == 'G') {
        gx = i;
        gy = j;
      }
    }
  }
  solve();
  return 0;
}


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

using namespace std;
typedef pair<int, int> pii;

#define S 'S'
#define X 'X'

#define W_MAX 1000

char map[W_MAX][W_MAX];
bool visited[W_MAX][W_MAX];

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

  pii pos; // rat position

  for (int i = 0; i < H; i++) {
    getchar();
    for (int j = 0; j < W; j++) {
      scanf("%c", &map[i][j]);
      if (map[i][j] == S) {
        pos = make_pair(i, j);
      }
    }
  }

  int dx[] = {0, -1, 0, 1};
  int dy[] = {-1, 0, 1, 0};
  int ans = 0;
  int next = 1; // next target num

  while (next <= N) {
    memset(visited, false, sizeof(visited));

    queue<pair<pii, int>> q; //<pos, depth>
    q.push(make_pair(pos, 0));

    while (true) {
      pair<pii, int> p = q.front();
      q.pop();
      bool found = false;
      visited[p.first.first][p.first.second] = true;
      for (int i = 0; i < 4; i++) {
        int nx = p.first.first + dx[i], ny = p.first.second + dy[i];
        if (nx >= 0 && nx < H && ny >= 0 && ny < W && !visited[nx][ny]) {
          visited[nx][ny] = true;
          if (map[nx][ny] == '0' + next) {
            found = true;
            pos = make_pair(nx, ny);
            break;
          } else if (map[nx][ny] != X && map[nx][ny] != S) {
            q.push(make_pair(make_pair(nx, ny), p.second + 1));
          }
        }
      }
      if (found) {
        ans += p.second + 1;
        next++;
        break;
      }
    }
  }

  cout << ans << endl;
}

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

using namespace std;
typedef pair<int, int> pii;

#define S 'S'
#define X 'X'

#define W_MAX 1000

char map[W_MAX][W_MAX];
bool visited[W_MAX][W_MAX];

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

  pii pos; // rat position

  for (int i = 0; i < H; i++) {
    getchar();
    for (int j = 0; j < W; j++) {
      scanf("%c", &map[i][j]);
      if (map[i][j] == S) {
        pos = make_pair(i, j);
      }
    }
  }

  int dx[] = {0, -1, 0, 1};
  int dy[] = {-1, 0, 1, 0};
  int ans = 0;
  int next = 1; // next target num

  while (next <= N) {
    for (int i = 0; i < H; i++)
      for (int j = 0; j < W; j++)
        visited[i][j] = false;

    queue<pair<pii, int>> q; //<pos, depth>
    q.push(make_pair(pos, 0));

    while (true) {
      pair<pii, int> p = q.front();
      q.pop();
      bool found = false;
      visited[p.first.first][p.first.second] = true;
      for (int i = 0; i < 4; i++) {
        int nx = p.first.first + dx[i], ny = p.first.second + dy[i];
        if (nx >= 0 && nx < H && ny >= 0 && ny < W &&
            visited[nx][ny] == false) {
          visited[nx][ny] = true;
          if (map[nx][ny] == '0' + next) {
            found = true;
            pos = make_pair(nx, ny);
            break;
          } else if (map[nx][ny] != X) {
            q.push(make_pair(make_pair(nx, ny), p.second + 1));
          }
        }
      }
      if (found) {
        ans += p.second + 1;
        next++;
        break;
      }
    }
    while (!q.empty())
      q.pop();
  }

  cout << ans << endl;
}


#include <algorithm>
#include <cmath>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <stdio.h>
#include <string.h>
#include <string>
#include <vector>

using namespace std;

struct node {
  int x;
  int y;
  int dist;

  node(int x, int y, int dist) {
    this->x = x;
    this->y = y;
    this->dist = dist;
  }
};

bool vis[1010][1010];
char input[1010][1010];
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0, -1};
queue<node> q;

bool inArea(int x, int y, int n, int m) {
  return x >= 0 && x < n && y >= 0 && y < m;
}

int solve(int sx, int sy, int h, int w, int n) {
  while (!q.empty())
    q.pop();

  int value = 1;
  q.push(node(sx, sy, 0));
  vector<node> prev;

  while (!q.empty()) {
    node no = q.front();
    q.pop();
    vis[no.x][no.y] = true;

    prev.push_back(node(no.x, no.y, no.dist));

    if (input[no.x][no.y] >= '0' && input[no.x][no.y] <= '9' &&
        ((input[no.x][no.y] - '0') == value)) {
      value++;
      if (value == n + 1)
        return no.dist;

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

      for (int i = 0; i < prev.size() - 1; i++)
        vis[prev[i].x][prev[i].y] = false;
      prev.clear();
    }
    for (int i = 0; i < 4; i++) {
      int tx = no.x + dx[i];
      int ty = no.y + dy[i];
      if (inArea(tx, ty, h, w) && !vis[tx][ty] && input[tx][ty] != 'X')
        q.push(node(tx, ty, no.dist + 1));
    }
  }
  return -1;
}

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

    int sx, sy;
    for (i = 0; i < h; i++) {
      scanf("%s", input[i]);
      for (j = 0; j < w; j++) {
        if (input[i][j] == 'S') {
          sx = i;
          sy = j;
        }
      }
    }
    // ???S????§????
    printf("%d\\n", solve(sx, sy, h, w, n));
  }
  return 0;
}

#include <algorithm>
#include <cmath>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <stdio.h>
#include <string.h>
#include <string>
#include <vector>

using namespace std;

struct node {
  int x;
  int y;
  int dist;

  node(int x, int y, int dist) {
    this->x = x;
    this->y = y;
    this->dist = dist;
  }
};

bool vis[1010][1010];
char input[1010][1010];
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0, -1};
queue<node> q;

bool inArea(int x, int y, int n, int m) {
  return x >= 0 && x < n && y >= 0 && y < m;
}

int solve(int sx, int sy, int h, int w, int n) {
  while (!q.empty())
    q.pop();

  int value = 1;
  q.push(node(sx, sy, 0));
  vis[sx][sy] = true;

  while (!q.empty()) {
    node no = q.front();
    q.pop();

    if (input[no.x][no.y] >= '0' && input[no.x][no.y] <= '9' &&
        ((input[no.x][no.y] - '0') == value)) {
      value++;
      if (value == n + 1)
        return no.dist;

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

      for (int i = 0; i < h; i++)
        for (int j = 0; j < w; j++)
          vis[i][j] = false;
      vis[no.x][no.y] = true;
    }
    for (int i = 0; i < 4; i++) {
      int tx = no.x + dx[i];
      int ty = no.y + dy[i];
      if (inArea(tx, ty, h, w) && !vis[tx][ty] && input[tx][ty] != 'X') {
        vis[tx][ty] = true;
        q.push(node(tx, ty, no.dist + 1));
      }
    }
  }
  return -1;
}

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

    int sx, sy;
    for (i = 0; i < h; i++) {
      scanf("%s", input[i]);
      for (j = 0; j < w; j++) {
        if (input[i][j] == 'S') {
          sx = i;
          sy = j;
        }
      }
    }

    // ???S????§????
    printf("%d\\n", solve(sx, sy, h, w, n));
  }
  return 0;
}


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

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

const int vecx[4] = {1, 0, -1, 0};
const int vecy[4] = {0, -1, 0, 1};
int h, w, n;
T goal[10];
char filed[1000][1000];
int si, sj;
int ans;
int dis[1000][1000];

void bfs(T _goal, T _start) {
  std::queue<T> q;
  q.push(_start);
  while (q.size()) {
    T tmp = q.front();
    q.pop();
    if (tmp == _goal) {
      ans += dis[_goal.first][_goal.second];
      break;
    }
    int x = tmp.first;
    int y = tmp.second;
    for (int i = 0; i < 4; i++) {
      if (x + vecx[i] < 0 || x + vecx[i] >= h || y + vecy[i] < 0 ||
          y + vecy[i] >= w)
        continue;
      if (filed[x + vecx[i]][y + vecy[i]] != 'X') {
        dis[x + vecx[i]][y + vecy[i]] = dis[x][y] + 1;
        q.push(std::make_pair(x + vecx[i], y + vecy[i]));
      }
    }
  }
}

int main() {
  std::cin >> h >> w >> n;
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      std::cin >> filed[i][j];
      if (filed[i][j] == 'S') {
        goal[0].first = i;
        goal[0].second = j;
      }
      if (filed[i][j] > '0' && filed[i][j] <= '9') {
        goal[filed[i][j] - '0'].first = i;
        goal[filed[i][j] - '0'].second = j;
      }
    }
  }

  for (int i = 0; i < n; i++) {
    bfs(goal[i + 1], goal[i]);
    for (int j = 0; j < h; j++)
      for (int k = 0; k < w; k++)
        dis[j][k] = 0;
  }
  std::cout << ans << std::endl;
  return 0;
}

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

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

const int vecx[4] = {1, 0, -1, 0};
const int vecy[4] = {0, -1, 0, 1};
int h, w, n;
T goal[10];
char filed[1000][1000];
int si, sj;
int ans;
int dis[1000][1000];

void bfs(T _goal, T _start) {
  std::queue<T> q;
  q.push(_start);
  while (q.size()) {
    T tmp = q.front();
    q.pop();
    if (tmp == _goal) {
      ans += dis[_goal.first][_goal.second];
      break;
    }
    int x = tmp.first;
    int y = tmp.second;
    for (int i = 0; i < 4; i++) {
      if (x + vecx[i] < 0 || x + vecx[i] >= h || y + vecy[i] < 0 ||
          y + vecy[i] >= w)
        continue;
      if (filed[x + vecx[i]][y + vecy[i]] != 'X' &&
          !dis[x + vecx[i]][y + vecy[i]]) {
        dis[x + vecx[i]][y + vecy[i]] = dis[x][y] + 1;
        q.push(std::make_pair(x + vecx[i], y + vecy[i]));
      }
    }
  }
}

int main() {
  std::cin >> h >> w >> n;
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      std::cin >> filed[i][j];
      if (filed[i][j] == 'S') {
        goal[0].first = i;
        goal[0].second = j;
      }
      if (filed[i][j] > '0' && filed[i][j] <= '9') {
        goal[filed[i][j] - '0'].first = i;
        goal[filed[i][j] - '0'].second = j;
      }
    }
  }

  for (int i = 0; i < n; i++) {
    bfs(goal[i + 1], goal[i]);
    for (int j = 0; j < h; j++)
      for (int k = 0; k < w; k++)
        dis[j][k] = 0;
  }
  std::cout << ans << std::endl;
  return 0;
}


#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <complex>
#include <iomanip> // << fixed << setprecision(xxx)
#include <iostream>
#include <map> // if (M.find(key) != M.end()) { }
#include <queue>
#include <set> // S.insert(M);
#include <stack>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <tuple>  // get<n>(xxx)
#include <vector>
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <cassert>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
#include <random>  // random_device rd; mt19937 mt(rd());
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end

typedef long long ll;

class UnionFind {
public:
  int N;
  int *root;
  int *rank;

  UnionFind(int n) : N(n) {
    root = new int[N];
    rank = new int[N];
    for (auto i = 0; i < N; ++i) {
      root[i] = i;
      rank[i] = 0;
    }
  }

  ~UnionFind() {
    delete[] root;
    delete[] rank;
  }

  int find(int x) {
    if (root[x] == x)
      return x;
    return root[x] = find(root[x]);
  }

  void unite(int x, int y) {
    x = find(x);
    y = find(y);
    if (x == y)
      return;
    if (rank[x] < rank[y]) {
      root[x] = y;
    } else {
      root[y] = x;
      if (rank[x] == rank[y])
        ++(rank[x]);
    }
  }

  bool same(int x, int y) { return (find(x) == find(y)); }
};

class Edge {
public:
  int src, dst;
  ll cost;
  Edge(int s, int d, ll c) : src(s), dst(d), cost(c) {}
  friend bool operator<(const Edge &x, const Edge &y) {
    return x.cost < y.cost;
  }
  friend bool operator>(const Edge &x, const Edge &y) {
    return x.cost > y.cost;
  }
};

typedef Edge State;

class Graph {
public:
  static const ll infty = 100000000000000000;
  int N;
  vector<Edge> *V;
  vector<Edge> edges;
  // dfs
  vector<int> dfs_start;
  int *dfs_visited;
  int *dfs_from;
  int dfs_time;
  int *dfs_time_d;
  int *dfs_time_f;
  // dfs ??§ ??£?????????????±???????
  int *component;
  vector<vector<int>> c_components;
  // bfs
  vector<int> bfs_start;
  int *bfs_visited;
  int *bfs_from;
  ll *bfs_dist;
  // kruskal
  ll kruskal_cost;
  vector<Edge> *kruskal_V;
  vector<Edge> kruskal_W;
  // bellman_ford, dijkstra
  set<int> sh_start;
  ll **sh_dist;
  int **sh_prev;

  Graph(int n) : N(n), dfs_time(0), kruskal_cost(-1) {
    V = new vector<Edge>[N];
    component = new int[N];
    dfs_visited = new int[N];
    fill(dfs_visited, dfs_visited + N, 0);
    dfs_from = new int[N];
    dfs_time_d = new int[N];
    dfs_time_f = new int[N];
    bfs_visited = new int[N];
    fill(bfs_visited, bfs_visited + N, 0);
    bfs_from = new int[N];
    bfs_dist = new ll[N];
    kruskal_V = new vector<Edge>[N];
    sh_dist = new ll *[N];
    sh_prev = new int *[N];
  }
  ~Graph() {
    delete[] V;
    delete[] component;
    delete[] dfs_visited;
    delete[] dfs_from;
    delete[] dfs_time_d;
    delete[] dfs_time_f;
    delete[] bfs_visited;
    delete[] bfs_from;
    delete[] bfs_dist;
    delete[] kruskal_V;
    for (auto x : sh_start) {
      delete[] sh_dist[x];
      delete[] sh_prev[x];
    }
    delete[] sh_dist;
    delete[] sh_prev;
  }

  void add_edge(int src, int dst, ll cost = 1) {
    Edge e(src, dst, cost);
    V[src].push_back(e);
    edges.push_back(e);
  }

  vector<int> dfs(int start) {
    vector<int> ans;
    stack<State> S;
    S.push(State(-1, start, 0));
    dfs_start.push_back(start);
    while (!S.empty()) {
      State s = S.top();
      S.pop();
      if (dfs_visited[s.dst] == 0) {
        dfs_visited[s.dst] = 1;
        dfs_time_d[s.dst] = dfs_time++;
        dfs_from[s.dst] = s.src;
        component[s.dst] = start;
        ans.push_back(s.dst);
        S.push(s);
        for (auto x : V[s.dst]) {
          if (dfs_visited[x.dst] == 0) {
            S.push(State(s.dst, x.dst, s.cost + x.cost));
          }
        }
      } else if (dfs_visited[s.dst] == 1) {
        dfs_visited[s.dst] = 2;
        dfs_time_f[s.dst] = dfs_time++;
      }
    }
    return ans;
  }

  void make_c_components() {
    for (auto i = 0; i < N; ++i) {
      if (dfs_visited[i] > 0)
        continue;
      c_components.push_back(dfs(i));
    }
  }

  bool is_connected(int s, int t) {
    if (dfs_visited[s] == 0 || dfs_visited[t] == 0) {
      make_c_components();
    }
    return (component[s] == component[t]);
  }

  void bfs() {
    assert(!bfs_start.empty());
    queue<State> Q;
    for (auto x : bfs_start) {
      Q.push(State(-1, x, 0));
    }
    while (!Q.empty()) {
      State s = Q.front();
      Q.pop();
      if (bfs_visited[s.dst] == 0) {
        bfs_visited[s.dst] = 1;
        bfs_from[s.dst] = s.src;
        bfs_dist[s.dst] = s.cost;
        for (auto x : V[s.dst]) {
          if (bfs_visited[x.dst] == 0) {
            Q.push(State(s.dst, x.dst, s.cost + x.cost));
          }
        }
      }
    }
  }

  int kruskal() {
    if (kruskal_cost != -1)
      return kruskal_cost;
    sort(edges.begin(), edges.end());
    UnionFind u(N);
    int kruskal_cost = 0;
    for (auto e : edges) {
      if (!u.same(e.src, e.dst)) {
        kruskal_V[e.src].push_back(e);
        kruskal_W.push_back(e);
        u.unite(e.src, e.dst);
        kruskal_cost += e.cost;
      }
    }
    return kruskal_cost;
  }

  void new_sh_dist(int i) {
    if (sh_start.find(i) == sh_start.end()) {
      sh_dist[i] = new ll[N];
      sh_prev[i] = new int[N];
      sh_start.insert(i);
    }
  }

  void bellman_ford(int s) {
    new_sh_dist(s);
    for (auto i = 0; i < N; ++i) {
      sh_dist[s][i] = infty;
    }
    sh_dist[s][s] = 0;
    sh_prev[s][s] = -1;
    while (true) {
      bool update = false;
      for (auto e : edges) {
        if (sh_dist[s][e.src] != infty &&
            sh_dist[s][e.dst] > sh_dist[s][e.src] + e.cost) {
          sh_dist[s][e.dst] = sh_dist[s][e.src] + e.cost;
          sh_prev[s][e.dst] = e.src;
          update = true;
        }
      }
      if (!update)
        break;
    }
  }

  void dijkstra(int s) {
    new_sh_dist(s);
    for (auto i = 0; i < N; ++i) {
      sh_dist[s][i] = infty;
    }
    priority_queue<Edge, vector<Edge>, greater<Edge>> Q;
    Q.push(State(-1, s, 0));
    while (!Q.empty()) {
      State now = Q.top();
      Q.pop();
      if (sh_dist[s][now.dst] == infty) {
        sh_dist[s][now.dst] = now.cost;
        sh_prev[s][now.dst] = now.src;
        for (auto e : V[now.dst]) {
          if (sh_dist[s][e.dst] == infty) {
            Q.push(State(e.src, e.dst, e.cost + now.cost));
          }
        }
      }
    }
  }

  vector<int> get_shortest_path(int s, int t) {
    vector<int> path;
    for (; t != -1; t = sh_prev[s][t])
      path.push_back(t);
    reverse(path.begin(), path.end());
    return path;
  }
};

class Grid : public Graph {
public:
  int H;
  int W;
  static const int dx[], dy[];
  typedef tuple<int, int> point;

  Grid(int h, int w) : Graph(h * w), H(h), W(w) {}
  ~Grid() {}

  bool valid(int x, int y) { return (0 <= x && x < H && 0 <= y && y < W); }
  bool valid(point p) { return valid(get<0>(p), get<1>(p)); }

  int point_to_int(int x, int y) { return x * W + y; }
  int point_to_int(point p) { return point_to_int(get<0>(p), get<1>(p)); }

  static bool dammy_true(int x, int y, int z, int w) { return true; }
  static int dammy_one(int x, int y, int z, int w) { return 1; }

  void make_grid_graph(bool func(int, int, int, int) = dammy_true,
                       int func2(int, int, int, int) = dammy_one) {
    for (auto i = 0; i < H; ++i) {
      for (auto j = 0; j < W; ++j) {
        for (auto k = 0; k < 4; ++k) {
          int x = i + dx[k];
          int y = j + dy[k];
          if (valid(x, y) && func(i, j, x, y)) {
            add_edge(point_to_int(i, j), point_to_int(x, y), func2(i, j, x, y));
          }
        }
      }
    }
  }
};

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

// const int C = 1e6+10;
// const ll M = 1000000007;

int H, W, N;
string S[1010];

bool can(int x, int y, int z, int w) { return (S[z][w] != 'X'); }

int main() {
  cin >> H >> W >> N;
  Grid g(H, W);
  for (auto i = 0; i < H; ++i) {
    cin >> S[i];
  }
  g.make_grid_graph(can);
  tuple<int, int> P[10];
  for (auto i = 0; i < H; ++i) {
    for (auto j = 0; j < W; ++j) {
      int num = (S[i][j] - '0');
      if (1 <= num && num <= N) {
        P[num] = make_tuple(i, j);
      }
      if (S[i][j] == 'S') {
        P[0] = make_tuple(i, j);
      }
    }
  }
  int ans = 0;
  for (auto i = 0; i < N; ++i) {
    fill(g.bfs_visited, g.bfs_visited + g.N, 0);
    g.bfs_start.clear();
    g.bfs_start.push_back(g.point_to_int(P[i]));
    g.bfs();
    ans += g.bfs_dist[g.point_to_int(P[i + 1])];
  }
  cout << ans << endl;
}

/**
 * File    : JOI_2010_cheese.cpp
 * Author  : Kazune Takahashi
 * Created : 2018-3-8 21:40:42
 * Powered by Visual Studio Code
 */

#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <cassert>
#include <cctype>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <iomanip> // << fixed << setprecision(xxx)
#include <iostream>
#include <map> // if (M.find(key) != M.end()) { }
#include <queue>
#include <random> // random_device rd; mt19937 mt(rd());
#include <set>
#include <stack>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <tuple>
#include <vector>
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.

typedef long long ll;

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

// const int C = 1e6+10;
const int infty = 1000000007;

typedef tuple<int, int> point;

int H, W, N;
string S[1010];
int d[1010][1010];
point P[20];
queue<point> Q[20];

bool valid(int x, int y) {
  return (0 <= x && x < H && 0 <= y && y < W && S[x][y] != 'X');
}

int main() {
  cin >> H >> W >> N;
  for (auto i = 0; i < H; i++) {
    cin >> S[i];
  }
  for (auto i = 0; i < H; i++) {
    for (auto j = 0; j < W; j++) {
      if (S[i][j] == 'S') {
        P[0] = point(i, j);
      }
      int t = S[i][j] - '0';
      if (1 <= t && t <= 9) {
        P[t] = point(i, j);
      }
    }
  }
  int ans = 0;
  for (auto i = 0; i < N; i++) {
    fill(&d[0][0], &d[0][0] + 1010 * 1010, infty);
    d[get<0>(P[i])][get<1>(P[i])] = 0;
    Q[i].push(P[i]);
    while (!Q[i].empty()) {
      point p = Q[i].front();
      Q[i].pop();
      if (p == P[i + 1]) {
        ans += d[get<0>(p)][get<1>(p)];
#if DEBUG == 1
        cerr << "d[" << get<0>(p) << "][" << get<1>(p)
             << "] = " << d[get<0>(p)][get<1>(p)] << endl;
#endif
        break;
      }
      for (auto k = 0; k < 4; k++) {
        int nx = get<0>(p) + dx[k];
        int ny = get<1>(p) + dy[k];
        if (valid(nx, ny) && d[nx][ny] == infty) {
          d[nx][ny] = d[get<0>(p)][get<1>(p)] + 1;
          Q[i].push(point(nx, ny));
        }
      }
    }
  }
  cout << ans << endl;
}


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

#define rep(i, a, b) for (int i = (a); i < (b); i++)
#define pb push_back
#define mp(a, b) make_pair(a, b)
#define all(a) a.begin(), a.end()
#define pii pair<int, int>
#define ll long long
using namespace std;

#define MAX 10
#define SIZE 1000
#define INF 1 << 30

int H, W, N;
char sec[SIZE][SIZE + 1];
int move_cnt = INF;
int all_move_cnt = 0;
int dy[4] = {-1, 0, 1, 0};
int dx[4] = {0, 1, 0, -1};
int facy[10] = {};
int facx[10] = {};

struct state {
  int sy, sx, gy, gx, cnt;
  state() {}
  state(int _sy, int _sx, int _gy, int _gx, int _cnt)
      : sy(_sy), sx(_sx), gy(_gy), gx(_gx), cnt(_cnt) {}
};
queue<state> que;

void bfs() {
  int **tsec = new int *[SIZE];
  rep(i, 0, SIZE) tsec[i] = new int[SIZE + 1];
  rep(i, 0, SIZE) rep(j, 0, SIZE + 1) tsec[i][j] = INF;

  while (!que.empty()) {
    state ts = que.front();
    que.pop();
    // printf("sy=%d sx=%d gy=%d gx=%d
    // cnt=%d\\n",ts.sy,ts.sx,ts.gy,ts.gx,ts.cnt);
    if (ts.cnt > move_cnt)
      return;
    if (ts.sy == ts.gy && ts.sx == ts.gx) {
      move_cnt = min(move_cnt, ts.cnt);
      return;
    }
    tsec[ts.sy][ts.sx] = ts.cnt;

    rep(i, 0, 4) {
      int ny = ts.sy + dy[i];
      int nx = ts.sx + dx[i];
      if (ny < 0 || ny >= H)
        continue;
      if (nx < 0 || nx >= W)
        continue;
      if (sec[ny][nx] == 'X')
        continue;
      if (tsec[ny][nx] < ts.cnt)
        continue;
      state ns(ny, nx, ts.gy, ts.gx, ts.cnt + 1);
      que.push(ns);
    }
    // rep(i,0,H) { rep(j,0,W) tsec[i][j]>99?
    // printf("99"):printf("%2d",tsec[i][j]); cout << endl;}
  }

  rep(i, 0, SIZE) delete[] tsec[i];
  delete[] tsec;
}

void solve() {
  // rep(i,0,N+1) printf("%d y=%d x=%d\\n",i,facy[i],facx[i]);

  rep(i, 0, N) {
    move_cnt = INF;
    while (!que.empty())
      que.pop();
    state s(facy[i], facx[i], facy[i + 1], facx[i + 1], 0);
    que.push(s);
    // printf("\\n bfs start !! \\n");
    bfs();
    all_move_cnt += move_cnt;
  }

  cout << all_move_cnt << endl;
}

void input() {
  cin >> H >> W >> N;
  rep(i, 0, H) {
    rep(j, 0, W) {
      cin >> sec[i][j];
      if (sec[i][j] == 'S') {
        facy[0] = i;
        facx[0] = j;
      }
      if (sec[i][j] >= 49 && 57 >= sec[i][j]) {
        facy[sec[i][j] - 48] = i;
        facx[sec[i][j] - 48] = j;
      }
    }
  }
  solve();
}

int main(void) {
  input();

  return 0;
}

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

#define rep(i, a, b) for (int i = (a); i < (b); i++)
#define pb push_back
#define mp(a, b) make_pair(a, b)
#define all(a) a.begin(), a.end()
#define pii pair<int, int>
#define ll long long
using namespace std;

#define MAX 10
#define SIZE 1000
#define INF 1 << 30

int H, W, N;
char sec[SIZE][SIZE + 1];
int tsec[SIZE][SIZE + 1];
int move_cnt = INF;
int all_move_cnt = 0;
int facy[10] = {};
int facx[10] = {};
int gy, gx;

struct state {
  int sy, sx, cnt;
  state() {}
  state(int _sy, int _sx, int _cnt) : sy(_sy), sx(_sx), cnt(_cnt) {}
};
queue<state> que;

void bfs() {
  int dy[4] = {-1, 0, 1, 0};
  int dx[4] = {0, 1, 0, -1};
  rep(i, 0, SIZE) rep(j, 0, SIZE + 1) tsec[i][j] = INF;

  while (!que.empty()) {
    state ts = que.front();
    que.pop();
    // printf("sy=%d sx=%d cnt=%d\\n",ts.sy,ts.sx,ts.cnt);
    if (ts.sy == gy && ts.sx == gx) {
      move_cnt = min(move_cnt, ts.cnt);
      break;
    }

    int ny, nx;
    rep(i, 0, 4) {
      ny = ts.sy + dy[i];
      nx = ts.sx + dx[i];
      if (ny < 0 || ny >= H || nx < 0 || nx >= W)
        continue;
      if (sec[ny][nx] == 'X' || tsec[ny][nx] != INF)
        continue;
      state ns(ny, nx, ts.cnt + 1);
      tsec[ny][nx] = ts.cnt + 1;
      que.push(ns);
    }
    // rep(i,0,H) { rep(j,0,W) tsec[i][j]>99?
    // printf("99"):printf("%2d",tsec[i][j]); cout << endl;}
  }
}

void solve() {
  // rep(i,0,N+1) printf("%d y=%d x=%d\\n",i,facy[i],facx[i]);

  rep(i, 0, N) {
    move_cnt = INF;
    while (!que.empty())
      que.pop();
    state s(facy[i], facx[i], 0);
    que.push(s);
    gy = facy[i + 1];
    gx = facx[i + 1];
    // printf("\\n bfs start !! \\n");
    bfs();
    all_move_cnt += move_cnt;
  }

  cout << all_move_cnt << endl;
}

void input() {
  cin >> H >> W >> N;
  rep(i, 0, H) {
    rep(j, 0, W) {
      cin >> sec[i][j];
      if (sec[i][j] == 'S') {
        facy[0] = i;
        facx[0] = j;
      }
      if (sec[i][j] >= 49 && 57 >= sec[i][j]) {
        facy[sec[i][j] - 48] = i;
        facx[sec[i][j] - 48] = j;
      }
    }
  }
  solve();
}

int main(void) {
  input();

  return 0;
}


#include <algorithm>
#include <iostream>
#include <set>
#include <vector>
using namespace std;
int H, W, N;

char world[1002][1002];

pair<int, int> S;

vector<pair<int, int>> getNeighbors(pair<int, int> xs) {
  vector<pair<int, int>> v;
  int dx[4] = {1, 0, -1, 0};
  int dy[4] = {0, 1, 0, -1};
  for (int i = 0; i < 4; i++) {
    int nx = dx[i] + xs.first;
    int ny = dy[i] + xs.second;
    if (world[nx][ny] != 'X') {
      v.push_back(pair<int, int>(nx, ny));
    }
  }
  return v;
}

bool isAbnormal(vector<vector<int>> &trails, const pair<int, int> &xs) {
  if (trails[xs.first][xs.second]) {
    return false;
  } else {
    trails[xs.first][xs.second] = 1;
    return true;
  }
}

pair<int, pair<int, int>> solve(char goal, const vector<pair<int, int>> &v,
                                int depth) {
  vector<pair<int, int>> v2;
  vector<vector<int>> trails =
      vector<vector<int>>(H + 2, vector<int>(W + 2, 0));

  for (auto target : v) {
    vector<pair<int, int>> neighbors = getNeighbors(target);
    for (auto x : neighbors) {
      if (world[x.first][x.second] == goal) {
        return pair<int, pair<int, int>>(depth + 1, x);
      }
      if (isAbnormal(trails, x)) {
        v2.push_back(x);
      }
    }
  }
  return solve(goal, v2, depth + 1);
}

void input() {
  cin >> H >> W >> N;
  for (int i = 1; i < H + 1; i++) {
    for (int j = 1; j < W + 1; j++) {
      cin >> world[i][j];
      if (world[i][j] == 'S') {
        S = pair<int, int>(i, j);
      }
    }
  }
}

void init() {
  for (int j = 0; j < W + 2; j++) {
    world[0][j] = 'X';
    world[H + 1][j] = 'X';
  }
  for (int i = 0; i < H + 2; i++) {
    world[i][0] = 'X';
    world[i][W + 1] = 'X';
  }
}

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

  init();

  int sum = 0;
  for (char g = '1'; g < '1' + N; g++) {
    pair<int, pair<int, int>> res = solve(g, vector<pair<int, int>>(1, S), 0);
    sum += res.first;
    S = res.second;
  }

  cout << sum << endl;

  return 0;
}

#include <algorithm>
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
int H, W, N;

char world[1002][1002];

pair<int, int> S;

vector<pair<int, int>> getNeighbors(pair<int, int> xs) {
  vector<pair<int, int>> v;
  int dx[4] = {1, 0, -1, 0};
  int dy[4] = {0, 1, 0, -1};
  for (int i = 0; i < 4; i++) {
    int nx = dx[i] + xs.first;
    int ny = dy[i] + xs.second;
    if (world[nx][ny] != 'X') {
      v.push_back(pair<int, int>(nx, ny));
    }
  }
  return v;
}

bool isAbnormal(vector<vector<bool>> &trails, const pair<int, int> &xs) {
  if (trails[xs.first][xs.second]) {
    return false;
  } else {
    trails[xs.first][xs.second] = true;
    return true;
  }
}

// pair<int, pair<int, int> > solve(char goal, const vector<pair<int, int> >& v,
// int depth){
//     vector<pair<int, int> > v2;
//     vector<vector<bool> > trails = vector<vector<bool> >(H + 2,
//     vector<bool>(W + 2, false));

//     for(auto target: v){
//         vector<pair<int, int> > neighbors = getNeighbors(target);
//         for(auto x: neighbors){
//             if (world[x.first][x.second] == goal) {
//                 return pair<int, pair<int, int> >(depth + 1, x);
//             }
//             if (isAbnormal(trails, x)){
//                 v2.push_back(x);
//             }
//         }
//     }
//     return solve(goal, v2, depth + 1);
// }

pair<int, pair<int, int>> solve(char goal, pair<int, int> s) {
  vector<pair<int, int>> v2;
  vector<vector<bool>> trails =
      vector<vector<bool>>(H + 2, vector<bool>(W + 2, false));

  queue<pair<int, pair<int, int>>> q;
  q.push(pair<int, pair<int, int>>(0, s));

  pair<int, pair<int, int>> target;
  while (true) {
    target = q.front();
    q.pop();

    int depth = target.first;
    pair<int, int> xy = target.second;

    vector<pair<int, int>> neighbors = getNeighbors(xy);
    for (auto neighbor : neighbors) {
      int x = neighbor.first;
      int y = neighbor.second;
      if (world[x][y] == goal) {
        return pair<int, pair<int, int>>(depth + 1, neighbor);
      }
      if (isAbnormal(trails, neighbor)) {
        q.push(pair<int, pair<int, int>>(depth + 1, neighbor));
      }
    }
  }
}

void input() {
  cin >> H >> W >> N;
  for (int i = 1; i < H + 1; i++) {
    for (int j = 1; j < W + 1; j++) {
      cin >> world[i][j];
      if (world[i][j] == 'S') {
        S = pair<int, int>(i, j);
      }
    }
  }
}

void init() {
  for (int j = 0; j < W + 2; j++) {
    world[0][j] = 'X';
    world[H + 1][j] = 'X';
  }
  for (int i = 0; i < H + 2; i++) {
    world[i][0] = 'X';
    world[i][W + 1] = 'X';
  }
}

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

  init();

  int sum = 0;
  for (char g = '1'; g < '1' + N; g++) {
    pair<int, pair<int, int>> res = solve(g, S);
    sum += res.first;
    S = res.second;
  }

  cout << sum << endl;

  return 0;
}


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

using namespace std;

typedef pair<int, int> point;
typedef pair<point, int> kotori;
// 2130
static const int dx[] = {0, 0, 1, -1, 1, 1, -1, -1};
static const int dy[] = {1, -1, 0, 0, 1, -1, 1, -1};

bool vst[1280][1280];
string field[1280];
int h, w, n;

void vst_clear(void) {
  for (int i = 0; i < 1280; i++) {
    for (int j = 0; j < 1280; j++) {
      vst[i][j] = false;
    }
  }
}

bool is_region(int y, int x) {
  return (0 <= y) && (y < h) && (0 <= x) && (x < w);
}

int main(void) {
  ios::sync_with_stdio(0);
  cin.tie(0);

  point start, goal;
  point f[10];

  cin >> h >> w >> n;
  for (int i = 0; i < h; i++) {
    cin >> field[i];
    for (int j = 0; j < w; j++) {
      if (field[i][j] == 'S') {
        field[i][j] = '0';
      }
      if (isdigit(field[i][j])) {
        f[field[i][j] - '0'] = make_pair(i, j);
      }
    }
  }

  int ret = 0;
  for (int g = 1; g <= n; g++) {
    vst_clear();
    start = f[g - 1];
    goal = f[g];
    vst[start.first][start.second] = true;

    queue<kotori> q;
    kotori a;
    a.first = start;
    a.second = 0;
    q.push(a);
    // point, step;
    while (!q.empty()) {
      kotori hanayo = q.front();
      q.pop();
      vst[hanayo.first.first][hanayo.first.second] = true;
      if (hanayo.first == goal) {
        ret += hanayo.second;
        break;
      }
      for (int i = 0; i < 4; i++) {
        int ny = hanayo.first.first + dy[i], nx = hanayo.first.second + dx[i];
        if (!is_region(ny, nx))
          continue;
        if (vst[ny][nx])
          continue;
        if (field[ny][nx] == 'X')
          continue;
        kotori p;
        p.first = make_pair(ny, nx);
        p.second = hanayo.second + 1;
        q.push(p);
      }
    }
  }
  cout << ret << endl;

  return 0;
}

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

using namespace std;

typedef pair<int, int> point;
typedef pair<point, int> kotori;
// 2130
static const int dx[] = {0, 0, 1, -1, 1, 1, -1, -1};
static const int dy[] = {1, -1, 0, 0, 1, -1, 1, -1};

bool vst[1280][1280];
string field[1280];
int h, w, n;

void vst_clear(void) {
  for (int i = 0; i < 1280; i++) {
    for (int j = 0; j < 1280; j++) {
      vst[i][j] = false;
    }
  }
}

bool is_region(int y, int x) {
  return (0 <= y) && (y < h) && (0 <= x) && (x < w);
}

int main(void) {
  // ios::sync_with_stdio(0); cin.tie(0);

  point start, goal;
  point f[10];

  cin >> h >> w >> n;
  for (int i = 0; i < h; i++) {
    cin >> field[i];
    cin.ignore();
    for (int j = 0; j < w; j++) {
      if (field[i][j] == 'S') {
        field[i][j] = '0';
      }
      if (isdigit(field[i][j])) {
        f[field[i][j] - '0'] = make_pair(i, j);
      }
    }
  }

  int ret = 0;
  for (int g = 1; g <= n; g++) {
    // cout << g-1 << " done" << endl;
    vst_clear();
    start = f[g - 1];
    goal = f[g];

    queue<kotori> q;
    kotori a;
    a.first = start;
    a.second = 0;
    q.push(a);
    // point, step;
    while (!q.empty()) {
      kotori hanayo = q.front();
      q.pop();
      int x = hanayo.first.second, y = hanayo.first.first;
      // cout << y << " " << x << endl;
      if (vst[y][x])
        continue;
      vst[y][x] = true;
      if (hanayo.first == goal) {
        ret += hanayo.second;
        break;
      }
      for (int i = 0; i < 4; i++) {
        int ny = hanayo.first.first + dy[i], nx = hanayo.first.second + dx[i];
        if (!is_region(ny, nx))
          continue;
        if (vst[ny][nx])
          continue;
        if (field[ny][nx] == 'X')
          continue;
        kotori p;
        p.first = make_pair(ny, nx);
        p.second = hanayo.second + 1;
        q.push(p);
      }
    }
  }
  cout << ret << endl;

  return 0;
}


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

struct mouse {
  int y, x, dis;
};

char stage[1000][1000];
int ng[1000][1000] = {};
int main() {
  int h, w, n;
  mouse s;
  s.dis = 0;
  cin >> h >> w >> n;
  for (int i = 0; i < h; i++) {
    cin >> stage[i];
    for (int j = 0; j < w; j++) {
      if (stage[i][j] == 'S') {
        s.y = i;
        s.x = j;
      } else if (stage[i][j] != 'X' && stage[i][j] != '.') {
        stage[i][j] -= '0';
      }
    }
  }

  int ny, nx;
  int situ_y[4] = {-1, 0, 1, 0}, situ_x[4] = {0, 1, 0, -1};
  for (int target = 1; target <= n; target++) {
    queue<mouse> mickey;
    mouse m_c;
    mickey.push(s);
    while (1) {
      m_c = mickey.front();
      if (stage[m_c.y][m_c.x] == target) {
        s.y = m_c.y;
        s.x = m_c.x;
        s.dis = m_c.dis;
        break;
      }
      if ((m_c.dis != 0 && ng[m_c.y][m_c.x] == m_c.dis) ||
          stage[m_c.y][m_c.x] == 'X') {
        mickey.pop();
        continue;
      }
      ng[m_c.y][m_c.x] = m_c.dis;
      for (int i = 0; i < 4; i++) {
        m_c = mickey.front();
        ny = m_c.y + situ_y[i];
        nx = m_c.x + situ_x[i];
        if (ny < 0 || h <= ny || nx < 0 || w <= nx)
          continue;
        m_c.y = ny;
        m_c.x = nx;
        m_c.dis++;
        mickey.push(m_c);
      }
      mickey.pop();
    }
  }
  printf("%d\\n", s.dis);
  return 0;
}

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

struct mouse {
  int y, x, dis;
  mouse() { y = x = dis = 0; }
};

char stage[1000][1000];
int ng[1000][1000] = {};
int main() {
  int h, w, n;
  mouse s;
  cin >> h >> w >> n;
  for (int i = 0; i < h; i++) {
    cin >> stage[i];
    for (int j = 0; j < w; j++) {
      if (stage[i][j] == 'S') {
        s.y = i;
        s.x = j;
      } else if (stage[i][j] != 'X' && stage[i][j] != '.') {
        stage[i][j] -= '0';
      }
    }
  }

  int ny, nx;
  int situ_y[4] = {-1, 0, 1, 0}, situ_x[4] = {0, 1, 0, -1};
  for (int target = 1; target <= n; target++) {
    queue<mouse> mickey;
    mouse m_c;
    for (int i = 0; i < h; i++)
      for (int j = 0; j < w; j++)
        ng[i][j] = 0;
    mickey.push(s);
    while (1) {
      m_c = mickey.front();
      if (stage[m_c.y][m_c.x] == target) {
        s = m_c;
        break;
      }
      if ((m_c.dis != 0 && ng[m_c.y][m_c.x] >= 4) ||
          stage[m_c.y][m_c.x] == 'X') {
        mickey.pop();
        continue;
      }
      ng[m_c.y][m_c.x]++;
      for (int i = 0; i < 4; i++) {
        m_c = mickey.front();
        ny = m_c.y + situ_y[i];
        nx = m_c.x + situ_x[i];
        if (ny < 0 || h <= ny || nx < 0 || w <= nx)
          continue;
        m_c.y = ny;
        m_c.x = nx;
        m_c.dis++;
        mickey.push(m_c);
      }
      mickey.pop();
    }
  }
  printf("%d\\n", s.dis);
  return 0;
}


#include <cmath>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <queue>
#include <string>
using namespace std;
int main() {
  int i, j;
  int a[1002][1002], c[10], d[10], n, w, h, x, y, z;
  int sm = 0;
  char s;
  bool b[1002][1002];
  queue<pair<pair<int, int>, int>> q;
  memset(a, -1, sizeof(a));
  cin >> h >> w >> n;
  for (i = 1; i < h + 1; i++) {
    for (j = 1; j < w + 1; j++) {
      cin >> s;
      if (s != 'X') {
        a[j][i] = 0;
        if (0) {
        } else if (s == '.') {
        } else if (s == 'S') {
          c[0] = j;
          d[0] = i;
        } else {
          c[s - '0'] = j;
          d[s - '0'] = i;
        }
      }
    }
  }
  for (i = 0; i < n; i++) {
    memset(b, 0, sizeof(b));
    while (q.empty() == 0)
      q.pop();
    q.push(make_pair(make_pair(c[i], d[i]), 0));
    for (;;) {
      x = q.front().first.first;
      y = q.front().first.second;
      z = q.front().second;
      q.pop();
      if (a[x][y] != -1 && b[x][y] == 0) {
        if (x == c[i + 1] && y == d[i + 1])
          break;
        b[x][y] = 1;
        q.push(make_pair(make_pair(x - 1, y), z + 1));
        q.push(make_pair(make_pair(x, y - 1), z + 1));
        q.push(make_pair(make_pair(x + 1, y), z + 1));
        q.push(make_pair(make_pair(x, y + 1), z + 1));
      }
    }
    sm += z;
  }
  cout << sm << endl;
  return 0;
}


#include <algorithm> // other
#include <bitset>
#include <cassert> // c
#include <complex>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream> // io
#include <map>
#include <numeric>
#include <queue>
#include <random>
#include <regex>
#include <set>
#include <sstream>
#include <stack>
#include <vector> // container
using namespace std;

typedef long long ll;

#define ALL(c) (begin(c)), (end(c))
#define REP(i, n) FOR(i, 0, n)
#define REPr(i, n) FORr(i, 0, n)
#define FOR(i, l, r) for (int i = (int)(l); i < (int)(r); ++i)
#define FORr(i, l, r) for (int i = (int)(r)-1; i >= (int)(l); --i)
#define EACH(it, o) for (auto it = (o).begin(); it != (o).end(); ++it)
#define IN(l, v, r) ((l) <= (v) && (v) < (r))
#define UNIQUE(v) v.erase(unique(ALL(v)), v.end())
// debug
#define DUMP(x) cerr << #x << " = " << (x)
#define LINE() cerr << " (L" << __LINE__ << ")"

class range {
private:
  struct Iter {
    int v;
    int operator*() { return v; }
    bool operator!=(Iter &itr) { return v < itr.v; }
    void operator++() { ++v; }
  };
  Iter i, n;

public:
  range(int n) : i({0}), n({n}) {}
  range(int i, int n) : i({i}), n({n}) {}
  Iter &begin() { return i; }
  Iter &end() { return n; }
};

// output
template <typename T> ostream &operator<<(ostream &os, const vector<T> &as) {
  REP(i, as.size()) {
    if (i != 0)
      os << " ";
    os << as[i];
  }
  return os;
}
template <typename T>
ostream &operator<<(ostream &os, const vector<vector<T>> &as) {
  REP(i, as.size()) {
    if (i != 0)
      os << endl;
    os << as[i];
  }
  return os;
}
template <typename T> ostream &operator<<(ostream &os, const set<T> &ss) {
  for (auto a : ss) {
    if (a != ss.begin())
      os << " ";
    os << a;
  }
  return os;
}
template <typename T1, typename T2>
ostream &operator<<(ostream &os, const pair<T1, T2> &p) {
  os << p.first << " " << p.second;
  return os;
}
template <typename K, typename V>
ostream &operator<<(ostream &os, const map<K, V> &m) {
  bool isF = true;
  for (auto &p : m) {
    if (!isF)
      os << endl;
    os << p;
    isF = false;
  }
  return os;
}
template <typename T1> ostream &operator<<(ostream &os, const tuple<T1> &t) {
  os << get<0>(t);
  return os;
}
template <typename T1, typename T2>
ostream &operator<<(ostream &os, const tuple<T1, T2> &t) {
  os << get<0>(t) << " " << get<1>(t);
  return os;
}
template <typename T1, typename T2, typename T3>
ostream &operator<<(ostream &os, const tuple<T1, T2, T3> &t) {
  os << get<0>(t) << " " << get<1>(t) << " " << get<2>(t);
  return os;
}
template <typename T1, typename T2, typename T3, typename T4>
ostream &operator<<(ostream &os, const tuple<T1, T2, T3, T4> &t) {
  os << get<0>(t) << " " << get<1>(t) << " " << get<2>(t) << " " << get<3>(t);
  return os;
}
template <typename T1, typename T2, typename T3, typename T4, typename T5>
ostream &operator<<(ostream &os, const tuple<T1, T2, T3, T4, T5> &t) {
  os << get<0>(t) << " " << get<1>(t) << " " << get<2>(t) << " " << get<3>(t)
     << " " << get<4>(t);
  return os;
}
template <typename T1, typename T2, typename T3, typename T4, typename T5,
          typename T6>
ostream &operator<<(ostream &os, const tuple<T1, T2, T3, T4, T5, T6> &t) {
  os << get<0>(t) << " " << get<1>(t) << " " << get<2>(t) << " " << get<3>(t)
     << " " << get<4>(t) << " " << get<5>(t);
  return os;
}
template <typename T1, typename T2, typename T3, typename T4, typename T5,
          typename T6, typename T7>
ostream &operator<<(ostream &os, const tuple<T1, T2, T3, T4, T5, T6, T7> &t) {
  os << get<0>(t) << " " << get<1>(t) << " " << get<2>(t) << " " << get<3>(t)
     << " " << get<4>(t) << " " << get<5>(t) << " " << get<6>(t);
  return os;
}

// input
char tmp[1000];
#define nextInt(n) scanf("%d", &n)
#define nextLong(n) scanf("%lld", &n) // I64d
#define nextDouble(n) scanf("%lf", &n)
#define nextChar(n) scanf("%c", &n)
#define nextString(n)                                                          \\
  scanf("%s", tmp);                                                            \\
  n = tmp

// values
template <typename T> T INF() { assert(false); };
template <> int INF<int>() { return 1 << 28; };
template <> ll INF<ll>() { return 1LL << 58; };
template <> double INF<double>() { return 1e16; };

template <class T> T EPS() { assert(false); };
template <> int EPS<int>() { return 1; };
template <> ll EPS<ll>() { return 1LL; };
template <> double EPS<double>() { return 1e-8; };
template <> long double EPS<long double>() { return 1e-8; };

template <typename T, typename U> T pmod(T v, U M) { return (v % M + M) % M; }

int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};
class Main {
public:
  void run() {
    int H, W, N;
    cin >> H >> W >> N;
    vector<string> board(H);
    REP(i, H) cin >> board[i];

    int sy, sx;
    REP(y, H) REP(x, W) if (board[y][x] == 'S') {
      sy = y;
      sx = x;
    }

    int dp[H][W][N + 1];
    fill_n(dp[0][0], H * W * (N + 1), INF<int>());
    bool passed[H][W][N + 1];
    fill_n(passed[0][0], H * W * (N + 1), false);
    queue<tuple<int, int, int, int>> que;
    que.push(make_tuple(sy, sx, 0, 0));
    passed[sy][sx][0] = true;
    int res = INF<int>();
    while (!que.empty()) {
      auto t = que.front();
      que.pop();
      int y, x, n, c;
      tie(y, x, n, c) = t;
      if (n == N) {
        res = min(res, c);
        break;
      }
      REP(d, 4) {
        int nx = x + dx[d], ny = y + dy[d];
        if (IN(0, nx, W) && IN(0, ny, H)) {
          if (board[ny][nx] == (n + 1) + '0') {
            if (!passed[ny][nx][n + 1]) {
              que.push(make_tuple(ny, nx, n + 1, c + 1));
              passed[ny][nx][n + 1] = true;
            }
          } else if (board[ny][nx] != 'X') {
            if (!passed[ny][nx][n]) {
              que.push(make_tuple(ny, nx, n, c + 1));
              passed[ny][nx][n] = true;
            }
          }
        }
      }
    }
    cout << res << endl;
  }
};

int main() {
  cout << fixed << setprecision(20);
  cin.tie(0);
  ios::sync_with_stdio(false);
  Main().run();
  return 0;
}

#include <algorithm> // other
#include <bitset>
#include <cassert> // c
#include <complex>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream> // io
#include <map>
#include <numeric>
#include <queue>
#include <random>
#include <regex>
#include <set>
#include <sstream>
#include <stack>
#include <vector> // container
using namespace std;

typedef long long ll;

#define ALL(c) (begin(c)), (end(c))
#define REP(i, n) FOR(i, 0, n)
#define REPr(i, n) FORr(i, 0, n)
#define FOR(i, l, r) for (int i = (int)(l); i < (int)(r); ++i)
#define FORr(i, l, r) for (int i = (int)(r)-1; i >= (int)(l); --i)
#define EACH(it, o) for (auto it = (o).begin(); it != (o).end(); ++it)
#define IN(l, v, r) ((l) <= (v) && (v) < (r))
#define UNIQUE(v) v.erase(unique(ALL(v)), v.end())
// debug
#define DUMP(x) cerr << #x << " = " << (x)
#define LINE() cerr << " (L" << __LINE__ << ")"

class range {
private:
  struct Iter {
    int v;
    int operator*() { return v; }
    bool operator!=(Iter &itr) { return v < itr.v; }
    void operator++() { ++v; }
  };
  Iter i, n;

public:
  range(int n) : i({0}), n({n}) {}
  range(int i, int n) : i({i}), n({n}) {}
  Iter &begin() { return i; }
  Iter &end() { return n; }
};

// output
template <typename T> ostream &operator<<(ostream &os, const vector<T> &as) {
  REP(i, as.size()) {
    if (i != 0)
      os << " ";
    os << as[i];
  }
  return os;
}
template <typename T>
ostream &operator<<(ostream &os, const vector<vector<T>> &as) {
  REP(i, as.size()) {
    if (i != 0)
      os << endl;
    os << as[i];
  }
  return os;
}
template <typename T> ostream &operator<<(ostream &os, const set<T> &ss) {
  for (auto a : ss) {
    if (a != ss.begin())
      os << " ";
    os << a;
  }
  return os;
}
template <typename T1, typename T2>
ostream &operator<<(ostream &os, const pair<T1, T2> &p) {
  os << p.first << " " << p.second;
  return os;
}
template <typename K, typename V>
ostream &operator<<(ostream &os, const map<K, V> &m) {
  bool isF = true;
  for (auto &p : m) {
    if (!isF)
      os << endl;
    os << p;
    isF = false;
  }
  return os;
}
template <typename T1> ostream &operator<<(ostream &os, const tuple<T1> &t) {
  os << get<0>(t);
  return os;
}
template <typename T1, typename T2>
ostream &operator<<(ostream &os, const tuple<T1, T2> &t) {
  os << get<0>(t) << " " << get<1>(t);
  return os;
}
template <typename T1, typename T2, typename T3>
ostream &operator<<(ostream &os, const tuple<T1, T2, T3> &t) {
  os << get<0>(t) << " " << get<1>(t) << " " << get<2>(t);
  return os;
}
template <typename T1, typename T2, typename T3, typename T4>
ostream &operator<<(ostream &os, const tuple<T1, T2, T3, T4> &t) {
  os << get<0>(t) << " " << get<1>(t) << " " << get<2>(t) << " " << get<3>(t);
  return os;
}
template <typename T1, typename T2, typename T3, typename T4, typename T5>
ostream &operator<<(ostream &os, const tuple<T1, T2, T3, T4, T5> &t) {
  os << get<0>(t) << " " << get<1>(t) << " " << get<2>(t) << " " << get<3>(t)
     << " " << get<4>(t);
  return os;
}
template <typename T1, typename T2, typename T3, typename T4, typename T5,
          typename T6>
ostream &operator<<(ostream &os, const tuple<T1, T2, T3, T4, T5, T6> &t) {
  os << get<0>(t) << " " << get<1>(t) << " " << get<2>(t) << " " << get<3>(t)
     << " " << get<4>(t) << " " << get<5>(t);
  return os;
}
template <typename T1, typename T2, typename T3, typename T4, typename T5,
          typename T6, typename T7>
ostream &operator<<(ostream &os, const tuple<T1, T2, T3, T4, T5, T6, T7> &t) {
  os << get<0>(t) << " " << get<1>(t) << " " << get<2>(t) << " " << get<3>(t)
     << " " << get<4>(t) << " " << get<5>(t) << " " << get<6>(t);
  return os;
}

// input
char tmp[1000];
#define nextInt(n) scanf("%d", &n)
#define nextLong(n) scanf("%lld", &n) // I64d
#define nextDouble(n) scanf("%lf", &n)
#define nextChar(n) scanf("%c", &n)
#define nextString(n)                                                          \\
  scanf("%s", tmp);                                                            \\
  n = tmp

// values
template <typename T> T INF() { assert(false); };
template <> int INF<int>() { return 1 << 28; };
template <> ll INF<ll>() { return 1LL << 58; };
template <> double INF<double>() { return 1e16; };

template <class T> T EPS() { assert(false); };
template <> int EPS<int>() { return 1; };
template <> ll EPS<ll>() { return 1LL; };
template <> double EPS<double>() { return 1e-8; };
template <> long double EPS<long double>() { return 1e-8; };

template <typename T, typename U> T pmod(T v, U M) { return (v % M + M) % M; }

int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};
class Main {
public:
  void run() {
    int H, W, N;
    cin >> H >> W >> N;
    vector<string> board(H);
    REP(i, H) cin >> board[i];

    int sy, sx;
    REP(y, H) REP(x, W) if (board[y][x] == 'S') {
      sy = y;
      sx = x;
    }
    // bool passed[H][W][N+1]  くそ最適化
    int passed[H][W];
    REP(y, H) REP(x, W) passed[y][x] = 0;
    queue<tuple<int, int, int, int>> que;
    que.push(make_tuple(sy, sx, 0, 0));
    passed[sy][sx] |= (1 << 0);
    int res = INF<int>();
    while (!que.empty()) {
      auto t = que.front();
      que.pop();
      int y, x, n, c;
      tie(y, x, n, c) = t;
      if (n == N) {
        res = min(res, c);
        break;
      }
      REP(d, 4) {
        int nx = x + dx[d], ny = y + dy[d];
        if (IN(0, nx, W) && IN(0, ny, H)) {
          if (board[ny][nx] == (n + 1) + '0' && n + 1 <= N) {
            if (!(passed[ny][nx] & (1 << (n + 1)))) {
              que.push(make_tuple(ny, nx, n + 1, c + 1));
              passed[ny][nx] |= 1 << (n + 1);
            }
          } else if (board[ny][nx] != 'X') {
            if (!(passed[ny][nx] & (1 << n))) {
              que.push(make_tuple(ny, nx, n, c + 1));
              passed[ny][nx] |= 1 << n;
            }
          }
        }
      }
    }
    cout << res << endl;
  }
};

int main() {
  cout << fixed << setprecision(20);
  cin.tie(0);
  ios::sync_with_stdio(false);
  Main().run();
  return 0;
}


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

typedef long long ll;

using namespace std;

#define INF 1000000

int H, W, N;
int sx, sy;
int res = 0;
int d[1100][1100];
char maze[1100][1100];
pair<int, int> cheese[10];

void bfs(int HP) {
  queue<pair<int, int>> que;

  sx = cheese[HP - 1].first, sy = cheese[HP - 1].second;
  for (int i = 0; i < H; ++i) {
    for (int j = 0; j < W; ++j) {
      d[i][j] = INF;
    }
  }
  que.push(pair<int, int>(sx, sy));
  d[sx][sy] = 0;

  while (que.size()) {
    pair<int, int> p = que.front();
    que.pop();
    if ((maze[p.first][p.second] - '0') == HP)
      break;
    for (int dx = -1; dx <= 1; ++dx)
      for (int dy = -1; dy <= 1; ++dy) {
        if (abs(dx - dy) != 1)
          continue;
        int nx = p.first + dx, ny = p.second + dy;
        if (0 <= nx && nx < H && 0 <= ny && ny < W && maze[nx][ny] != 'X' &&
            d[nx][ny] == INF) {
          que.push(pair<int, int>(nx, ny));
          d[nx][ny] = d[p.first][p.second] + 1;
        }
      }
  }

  if (HP == N) {
    res += d[cheese[HP].first][cheese[HP].second];
    return;
  }

  res += d[cheese[HP].first][cheese[HP].second];
  bfs(HP + 1);
  return;
}

int main(void) {
  cin >> H >> W >> N;
  for (int i = 0; i < H; ++i) {
    for (int j = 0; j < W; ++j) {
      cin >> maze[i][j];
      if (maze[i][j] - '0' >= 1 && maze[i][j] - '0' <= N) {
        cheese[maze[i][j] - '0'] = pair<int, int>(i, j);
      } else if (maze[i][j] == 'S') {
        cheese[0] = pair<int, int>(i, j);
      }
    }
  }

  bfs(1);
  int r = res;
  cout << r << endl;
  while (1)
    ;
  return 0;
}

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

typedef long long ll;

using namespace std;

#define INF 1000000

int H, W, N;
int sx, sy;
int res = 0;
int d[1100][1100];
char maze[1100][1100];
pair<int, int> cheese[10];

void bfs(int HP) {
  queue<pair<int, int>> que;

  sx = cheese[HP - 1].first, sy = cheese[HP - 1].second;
  for (int i = 0; i < H; ++i) {
    for (int j = 0; j < W; ++j) {
      d[i][j] = INF;
    }
  }
  que.push(pair<int, int>(sx, sy));
  d[sx][sy] = 0;

  while (que.size()) {
    pair<int, int> p = que.front();
    que.pop();
    if ((maze[p.first][p.second] - '0') == HP)
      break;
    for (int dx = -1; dx <= 1; ++dx)
      for (int dy = -1; dy <= 1; ++dy) {
        if (abs(dx - dy) != 1)
          continue;
        int nx = p.first + dx, ny = p.second + dy;
        if (0 <= nx && nx < H && 0 <= ny && ny < W && maze[nx][ny] != 'X' &&
            d[nx][ny] == INF) {
          que.push(pair<int, int>(nx, ny));
          d[nx][ny] = d[p.first][p.second] + 1;
        }
      }
  }

  if (HP == N) {
    res += d[cheese[HP].first][cheese[HP].second];
    return;
  }

  res += d[cheese[HP].first][cheese[HP].second];
  bfs(HP + 1);
  return;
}

int main(void) {
  cin >> H >> W >> N;
  for (int i = 0; i < H; ++i) {
    for (int j = 0; j < W; ++j) {
      cin >> maze[i][j];
      if (maze[i][j] - '0' >= 1 && maze[i][j] - '0' <= N) {
        cheese[maze[i][j] - '0'] = pair<int, int>(i, j);
      } else if (maze[i][j] == 'S') {
        cheese[0] = pair<int, int>(i, j);
      }
    }
  }

  bfs(1);
  int r = res;
  cout << r << endl;
  return 0;
}


#include <algorithm>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <queue>
using namespace std;
int w, h, n;
char map[1024][1024];
int d[1024][1024];
const int direction[4][2] = {
    {-1, 0},
    {1, 0},
    {0, -1},
    {0, 1},
};
int factory[16][2];
typedef pair<int, int> P;
/*int bfs(int sx, int sy, int gx, int gy) {
    for (int i = 0; i < h; ++i) {
        for (int j = 0; j < w; ++j) {
            d[i][j] = -1;
        }
    }
    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 + direction[i][0];
            int ny = p.second + direction[i][1];
            if (0 <= nx && nx < h && 0 <= ny && ny < w && 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];
}*/
int bfs(int sx, int sy, int ex, int ey) {
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++)
      d[i][j] = -1;
  }
  queue<P> q;
  q.push(P(sx, sy));
  d[sx][sy] = 0;
  while (!q.empty()) {
    P p = q.front();
    q.pop();
    if (p.first == ex && p.second == ey)
      break;
    for (int i = 0; i < 4; i++) {
      int dx = p.first + direction[i][0];
      int dy = p.second + direction[i][1];
      if (dx >= 0 && dy >= 0 && dx < h && dy < w && map[dx][dy] != 'X' &&
          d[dx][dy] == -1)
        q.push(P(dx, dy));
      d[dx][dy] = d[p.first][p.second] + 1;
    }
  }
  return d[ex][ey];
}
/*int main() {

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

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

    return 0;
}*/
int main() {
  scanf("%d %d %d", &h, &w, &n);
  for (int i = 0; i < h; i++)
    scanf("%s", map[i]);
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      if (map[i][j] == 'S') {
        factory[0][0] = i;
        factory[0][1] = j;
        map[i][j] = '.';
      } else if (isdigit(map[i][j])) {
        factory[map[i][j] - '0'][0] = i;
        factory[map[i][j] - '0'][1] = j;
        map[i][j] = '.';
      }
    }
  }
  int ans = 0;
  for (int i = 0; i < n; i++)
    ans +=
        bfs(factory[i][0], factory[i][1], factory[i + 1][0], factory[i + 1][1]);
  printf("%d\\n", ans);
  return 0;
}
///////////////////////////End Sub//////////////////////////////////

#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
const int maxn = 1010;
const int dx[] = {-1, 1, 0, 0};
const int dy[] = {0, 0, -1, 1};
struct node {
  int x, y;
  int dep;
};
node q[maxn * maxn];
int a[maxn][maxn], vis[maxn][maxn];
int x[10], y[10];
int h, w, n;
int bfs(int s, int t) {
  memcpy(vis, a, sizeof(a)); // vis=a;
  q[0] = (node){x[s], y[s], 0};
  vis[x[s]][y[s]] = 1;
  int head = 0, tail = 1;
  while (head < tail) {
    node cur = q[head++];
    if (cur.x == x[t] && cur.y == y[t])
      return cur.dep;
    for (int i = 0; i < 4; i++) {
      int xx = cur.x + dx[i], yy = cur.y + dy[i];
      if (xx >= 0 && xx < h && yy >= 0 && yy < w && !vis[xx][yy]) {
        q[tail++] = (node){xx, yy, cur.dep + 1};
        vis[xx][yy] = 1;
      }
    }
  }
}
int main() {
  cin >> h >> w >> n;
  memset(a, 0, sizeof(a));
  for (int i = 0; i < h; i++)
    for (int j = 0; j < w; j++) {
      char ch;
      cin >> ch;
      if (ch == 'S') {
        x[0] = i;
        y[0] = j;
      }
      if (ch == 'X')
        a[i][j] = 1;
      if (ch >= '1' && ch <= '9') {
        x[ch - 48] = i;
        y[ch - 48] = j;
      }
    }
  int ans = 0, s;
  for (int i = 0; i < n; i++)
    ans += bfs(i, i + 1);
  cout << ans << endl;
  return 0;
}


#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <map>
#include <queue>
#include <stack>
#include <string>
#include <vector>
#define MAX_N 1000000
#define INF 1000000
using namespace std;

struct note {
  int x, y;
};
note start, ende;
typedef pair<int, int> P;
int H, W, N;
int sum;
int d[100][100];
char s[100][100];
int dx[4] = {0, 1, 0, -1};
int dy[4] = {1, 0, -1, 0};
void bfs(note t, note e) {
  queue<P> que;
  memset(d, -1, sizeof(d));
  int x = t.x;
  int y = t.y;
  d[x][y] = 0;
  que.push(P(x, y));
  while (!que.empty()) {
    P p = que.front();
    que.pop();
    int v = p.first;
    int u = p.second;
    for (int i = 0; i < 4; i++) {
      int xx = v + dx[i];
      int yy = u + dy[i];
      if (xx >= 0 && xx < H && yy >= 0 && yy < W && s[xx][yy] != 'X' &&
          d[xx][yy] == -1) {
        d[xx][yy] = d[v][u] + 1;
        que.push(P(xx, yy));
      }
    }
  }
  sum += d[e.x][e.y];
  start = e;
  return;
}
void solve() {
  for (int i = 0; i < H; i++) {
    for (int j = 0; j < W; j++) {
      if (s[i][j] == 'S') {
        start.x = i;
        start.y = j;
        i = H;
        j = W;
      }
    }
  }
  for (int k = 0; k < N; k++) {
    for (int i = 0; i < H; i++) {
      for (int j = 0; j < W; j++) {
        if (s[i][j] == 49 + k) {
          ende.x = i;
          ende.y = j;
          bfs(start, ende);
          i = H;
          j = W;
        }
      }
    }
  }
  printf("%d\\n", sum);
  return;
}
int main() {

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

#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <map>
#include <queue>
#include <stack>
#include <string>
#include <vector>
#define MAX_N 1000000
#define INF 0x3f3f3f3f
#define SIZE 1000
using namespace std;

struct note {
  int x, y;
} start, ende;
typedef pair<int, int> P;
int H, W, N;
char a[1003][1003];
int sum;
int d[1003][1003];
int dx[4] = {0, 1, 0, -1};
int dy[4] = {1, 0, -1, 0};
void bfs(note h, note m) {
  memset(d, -1, sizeof(d));
  queue<P> que;
  que.push(P(h.x, h.y));
  d[h.x][h.y] = 0;
  while (!que.empty()) {
    P p = que.front();
    que.pop();
    for (int i = 0; i < 4; i++) {
      int xx = p.first + dx[i];
      int yy = p.second + dy[i];
      if (xx >= 0 && xx < H && yy >= 0 && yy < W && a[xx][yy] != 'X' &&
          d[xx][yy] == -1) {
        d[xx][yy] = d[p.first][p.second] + 1;
        que.push(P(xx, yy));
      }
    }
  }
  sum += d[m.x][m.y];
  start = ende;
}
void solve() {
  for (int i = 0; i < H; i++) {
    for (int j = 0; j < W; j++) {
      if (a[i][j] == 'S') {
        start.x = i;
        start.y = j;
        i = H;
        j = W;
      }
    }
  }
  for (int k = 0; k < N; k++) {
    for (int i = 0; i < H; i++) {
      for (int j = 0; j < W; j++) {
        if (a[i][j] == k + 49) {
          ende.x = i;
          ende.y = j;
          bfs(start, ende);
          i = H;
          j = W;
        }
      }
    }
  }
  cout << sum << endl;
}
int main() {
  cin >> H >> W >> N;
  for (int i = 0; i < H; i++) {
    cin >> a[i];
  }
  sum = 0;
  solve();
  return 0;
}


#include <cstdio>
#include <cstring>
#include <iostream>
#include <queue>
using namespace std;
int H, W, N;
typedef pair<int, int> P;
#define INF 1e-9
const int MAX_N = 1001;
char maze[MAX_N][MAX_N];
bool vis[MAX_N][MAX_N];
int dx[4] = {0, 1, 0, -1};
int dy[4] = {1, 0, -1, 0};
int d[MAX_N][MAX_N];
bool right(int x, int y) {
  if (x >= 0 && x < H && y >= 0 && y < W && maze[x][y] != 'X' && !vis[x][y])
    return true;
  return false;
}
int bfs(int sx, int sy, int gx, int gy) {
  queue<P> que;
  for (int i = 0; i < H; i++) {
    for (int j = 0; j < W; j++)
      d[i][j] = INF;
  }
  que.push(P(sx, sy));
  d[sx][sy] = 0;
  while (que.size()) {
    P p = que.front();
    que.pop();
    if (p.first == gx && p.second == gy)
      break;
    for (int i = 0; i < 4; i++) {
      int nx = p.first + dx[i], ny = p.second + dy[i];
      if (right(nx, ny)) {
        que.push(P(nx, ny));
        d[nx][ny] = d[p.first][p.second] + 1;
      }
    }
  }
  return d[gx][gy];
}
int main() {
  while (scanf("%d%d%d", &H, &W, &N) != EOF) {
    getchar();
    for (int i = 0; i < H; i++)
      scanf("%s", maze[i]);
    int ans = 0;
    int sx = -1, sy = -1;
    for (int i = 0; i < H; i++) {
      for (int j = 0; j < W; j++)
        if (maze[i][j] == 'S') {
          sx = i;
          sy = j;
        }
      if (sx != -1 && sy != -1)
        break;
    }
    for (int i = 1; i <= N; i++) {
      memset(vis, false, sizeof(vis));
      int nx = -1, ny = -1;
      for (int j = 0; j < H; j++) {
        for (int k = 0; k < W; k++) {
          if (maze[j][k] == '0' + i) {
            nx = j;
            ny = k;
            break;
          }
        }
        if (nx != -1 && ny != -1)
          break;
      }
      ans += bfs(sx, sy, nx, ny);
      sx = nx;
      sy = ny;
    }
    printf("%d\\n", ans);
  }
  return 0;
}


#include <algorithm>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <set>
#include <vector>
using namespace std;
typedef long long ll;
typedef vector<int> vec;
typedef vector<vec> mat;
const int INF = 0x3f3f3f3f;
const int Mod = 1e9 + 7;
const double eps = 1e-7;
int dirX[4] = {1, 0, -1, 0};
int dirY[4] = {0, 1, 0, -1};
struct point {
  int x;
  int y;
  int depth;
  point() { x = y = depth = 0; }
  point(int X, int Y, int D) {
    x = X;
    y = Y;
    depth = D;
  }
  point(const point &p) {
    x = p.x;
    y = p.y;
    depth = p.depth;
  }
  bool operator==(const point &C) { return {x == C.x && y == C.y}; }
};
struct cheese : public point {
  int hard;
  cheese() { x = y = hard = 0; }
  cheese(int X, int Y, int H) {
    x = X;
    y = Y;
    hard = H;
  }
  bool operator<(const cheese &C) { return hard < C.hard; }
};
int main() {
  // ifstream ifs;
  // ifs.open("D:\\\\documents\\\\programDatas\\\\AOJ0558.txt");
  int H, W, N;
  cin >> H >> W >> N;
  bool a[1001][1001];
  bool v[1001][1001]; // here???
  memset(a, 0, sizeof(a));
  memset(v, 0, sizeof(v));
  vector<cheese> goal;
  for (int i = 1; i <= H; i++) {
    for (int j = 1; j <= W; j++) {
      char temp;
      cin >> temp;
      if (temp == 'S')
        goal.push_back(cheese(i, j, 0));
      else if (temp >= '1' && temp <= '9')
        goal.push_back(cheese(i, j, (int)(temp - 48)));
      else if (temp == '.')
        a[i][j] = 0;
      else if (temp == 'X')
        a[i][j] = 1;
    }
  }
  sort(goal.begin(), goal.end());
  // for debug
  /*for (int i = 1; i <= H; i++) {
          for (int j = 1; j <= W; j++) {
                  cout << setw(3) << a[i][j];
          }
          cout << endl;
  }
  for (int i = 0; i <= N; i++) {
          cout << goal[i].x << " " << goal[i].y << " " << goal[i].hard << " " <<
  endl;
  }
  cout << endl;
  */
  // BFS
  int total = 0;                // total steps
  for (int t = 0; t < N; t++) { // x for start point and x+1 for end point
    deque<point> que;
    que.push_back(point(goal[t].x, goal[t].y, 0));
    // for (int s = t + 2; s <= N; s++) {//mark harder cheese as visited !!
    //	v[goal[s].x][goal[s].y] = 1;
    // }
    while (!que.empty()) {

      point curP = que.front();
      que.pop_front();
      v[curP.x][curP.y] = 1; // as visited
      if (curP == goal[t + 1]) {
        total = total + curP.depth;
        memset(v, 0, sizeof(v));
        break;
      } else {
        for (int i = 0; i < 4; i++) {
          int tx = curP.x + dirX[i];
          int ty = curP.y + dirY[i];
          if (tx >= 1 && tx <= H && ty >= 1 && ty <= W && a[tx][ty] == 0 &&
              v[tx][ty] == 0)
            que.push_back(point(tx, ty, curP.depth + 1));
        }
      }
    }
  }
  cout << total << endl;
  return 0;
}

#include <bits/stdc++.h>

using namespace std;
typedef pair<int, int> P;
char maze[1005][1005];
int d[1005][1005];
int dirx[4] = {0, -1, 0, 1};
int diry[4] = {1, 0, -1, 0};
int h, w, n, hard;
int si, sj;
const int INF = 1 << 30;
int tot = 0;

void BFS(int ai, int aj) {
  queue<P> que;
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      d[i][j] = INF;
    }
  }
  que.push(P(ai, aj));
  d[ai][aj] = 0;
  while (!que.empty()) {
    P a = que.front();
    que.pop();
    int x = a.first, y = a.second;
    if (maze[x][y] - '0' == hard) {
      tot += d[x][y];
      si = x;
      sj = y;
      break;
    }
    for (int i = 0; i < 4; i++) {
      int dx = x + dirx[i], dy = y + diry[i];
      if (dx >= 0 && dx < h && dy >= 0 && dy < w && maze[dx][dy] != 'X' &&
          d[dx][dy] == INF) {
        d[dx][dy] = d[x][y] + 1;
        que.push(P(dx, dy));
      }
    }
  }
}

int main(int argc, char const *argv[]) {
  while (scanf("%d%d%d", &h, &w, &n) != EOF) {
    getchar();
    for (int i = 0; i < h; i++) {
      for (int j = 0; j < w; j++) {
        scanf("%c", &maze[i][j]);
        if (maze[i][j] == 'S') {
          si = i;
          sj = j;
        }
      }
      getchar();
    }
    tot = 0;
    hard = 1;
    for (int i = 0; i < n; i++) {
      BFS(si, sj);
      hard++;
    }
    cout << tot << endl;
  }
  return 0;
}


/* AOJ0558 Cheese */

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

using namespace std;

const int DIRECTSIZE = 4;
struct _direct {
  int drow;
  int dcol;
} direct[DIRECTSIZE] = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};

const int N = 1000;
const int N2 = 10;
char grid[N][N], visited[N][N];
int h, w, n;
struct _factory {
  int row, col;
} factory[N2 + 1];

struct _node {
  int row, col, level;
};

int bfs(int n) {
  _node start, temp;

  start.row = factory[n - 1].row;
  start.col = factory[n - 1].col;
  start.level = 0;
  visited[start.row][start.col] = 1;

  queue<_node> q;
  q.push(start);

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

    for (int i = 0; i <= DIRECTSIZE; i++) {
      int nextrow = front.row + direct[i].drow;
      int nextcol = front.col + direct[i].dcol;
      if (0 <= nextrow && nextrow < h && 0 <= nextcol && nextcol < w) {
        if (nextrow == factory[n].row && nextcol == factory[n].col) {
          return front.level + 1;
        } else if (visited[nextrow][nextcol] == 0 &&
                   grid[nextrow][nextcol] == '.') {
          visited[nextrow][nextcol] = 1;
          temp.row = nextrow;
          temp.col = nextcol;
          temp.level = front.level + 1;
          q.push(temp);
        }
      }
    }
  }

  return 0;
}

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

        if (grid[i][j] == 'S') {
          factory[0].row = i;
          factory[0].col = j;
          grid[i][j] = '.';
        } else if (isdigit(grid[i][j])) {
          factory[grid[i][j] - '0'].row = i;
          factory[grid[i][j] - '0'].col = j;
          grid[i][j] = '.';
        }
      }

    int minstep = 0;
    for (int i = 1; i <= n; i++) {
      memset(visited, 0, sizeof(visited));
      minstep += bfs(i);
    }

    cout << minstep << endl;
  }

  return 0;
}

#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;
}
///////////////////////////End Sub//////////////////////////////////


#include <bits/stdc++.h>
#define REP(i, n) for (int i = 0; i < n; i++)
#define REPR(i, n) for (int i = n; i >= 0; i--)
#define FOR(i, m, n) for (int i = m; i < n; i++)
#define FORR(i, m, n) for (int i = m; i >= n; i--)
#define SORT(v, n) sort(v, v + n);
#define VSORT(v) sort(v.begin(), v.end());
#define llong long long
#define pb(a) push_back(a)
#define INF 999999999
#define PB push_back
#define MP make_pair
using namespace std;
typedef pair<int, int> P;
typedef pair<llong, llong> LP;
typedef pair<int, P> PP;
typedef pair<llong, LP> LPP;

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

int r, c, n;
vector<P> cheese;

struct G {
  int grid[1000][1000];

public:
  void init() {
    REP(i, 1000) {
      REP(j, 1000) { grid[i][j] = -1; }
    }
    cin >> r >> c >> n;
    cheese.resize(n + 1);
    string line;
    REP(i, r) {
      cin >> line;
      REP(j, c) {
        switch (line[j]) {
        case 'X':
          grid[i + 1][j + 1] = -1;
          break;
        case '.':
          grid[i + 1][j + 1] = INF;
          break;
        case 'S':
          grid[i + 1][j + 1] = INF;
          cheese[0].first = i + 1;
          cheese[0].second = j + 1;
          break;
        default:
          int t = (int)line[j] - '0';
          cheese[t].first = i + 1;
          cheese[t].second = j + 1;
          grid[i + 1][j + 1] = INF;
        }
      }
    }
  }
};

int bfs(int sr, int sc, int gr, int gc, struct G g) {
  queue<P> q;
  q.push(MP(sr, sc));
  g.grid[sr][sc] = 0;
  int nr, nc;
  while (!q.empty()) {
    nr = q.front().first;
    nc = q.front().second;
    q.pop();
    if (nr == gr && nc == gc)
      return g.grid[nr][nc];
    REP(i, 4) {
      if (g.grid[nr + dy[i]][nc + dx[i]] == INF) {
        g.grid[nr + dy[i]][nc + dx[i]] = g.grid[nr][nc] + 1;
        q.push(MP(nr + dy[i], nc + dx[i]));
      }
    }
  }
  return 0;
}

int main() {
  struct G g;
  g.init();
  int ans = 0;
  REP(i, n) {
    ans += bfs(cheese[i].first, cheese[i].second, cheese[i + 1].first,
               cheese[i + 1].second, g);
  }
  cout << ans << endl;
  return 0;
}

#include <cctype>
#include <iostream>
#include <queue>

using namespace std;

int cnt;
char field[1002][1002];
int cost[1002][1002];
int factory[9][2];
int x[4] = {1, 0, -1, 0};
int y[4] = {0, 1, 0, -1};

int bfs(int sx, int sy, int gx, int gy) {
  queue<pair<int, int>> que;

  for (int i = 0; i < 1002; i++) {
    for (int j = 0; j < 1002; j++) {
      cost[i][j] = -1;
    }
  }

  que.push(make_pair(sx, sy));
  cost[sx][sy] = 0;

  while (!que.empty()) {
    pair<int, int> p;
    p = que.front();
    que.pop();

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

    for (int i = 0; i < 4; i++) {
      int tx = p.first + x[i];
      int ty = p.second + y[i];
      if (field[tx][ty] != 'X' && cost[tx][ty] == -1) {
        que.push(pair<int, int>(tx, ty));
        cost[tx][ty] = cost[p.first][p.second] + 1;
      }
    }
  }
  return cost[gx][gy];
}

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

  cin >> h >> w >> n;

  for (int y = 1; y <= h; y++) {
    for (int x = 1; x <= w; x++) {
      cin >> field[x][y];
      if (field[x][y] == 'S') {
        sx = x;
        sy = y;
      } else if (isdigit(field[x][y])) {
        int tmp = field[x][y] - '0';
        factory[tmp][0] = x;
        factory[tmp][1] = y;
      }
    }
    field[0][y] = 'X';
    field[w + 1][y] = 'X';
  }

  for (int x = 0; x <= w + 1; x++) {
    field[x][0] = 'X';
    field[x][h + 1] = 'X';
  }

  int cnt = 0;
  for (int i = 1; i <= n; i++) {
    // 次の目的地へ行くで
    cnt += bfs(sx, sy, factory[i][0], factory[i][1]);
    sx = factory[i][0];
    sy = factory[i][1];
  }

  cout << cnt << endl;
}


#include <iostream>
#include <vector>

using namespace std;

void recur(int i, int j, vector<vector<char>> &rect, vector<vector<int>> &dp) {
  try {
    if (rect.at(i - 1).at(j) != 'X' and dp[i - 1][j] > dp[i][j] + 1) {
      dp[i - 1][j] = dp[i][j] + 1;
      recur(i - 1, j, rect, dp);
    }
  } catch (...) {
  }
  try {
    if (rect.at(i + 1).at(j) != 'X' and dp[i + 1][j] > dp[i][j] + 1) {
      dp[i + 1][j] = dp[i][j] + 1;
      recur(i + 1, j, rect, dp);
    }
  } catch (...) {
  }
  try {
    if (rect.at(i).at(j - 1) != 'X' and dp[i][j - 1] > dp[i][j] + 1) {
      dp[i][j - 1] = dp[i][j] + 1;
      recur(i, j - 1, rect, dp);
    }
  } catch (...) {
  }
  try {
    if (rect.at(i).at(j + 1) != 'X' and dp[i][j + 1] > dp[i][j] + 1) {
      dp[i][j + 1] = dp[i][j] + 1;
      recur(i, j + 1, rect, dp);
    }
  } catch (...) {
  }
  return;
}

int trvrs(int sx, int sy, int gx, int gy, vector<vector<char>> &R,
          vector<vector<int>> dp) {
  dp[sx][sy] = 0;
  recur(sx, sy, R, dp);
  return dp[gx][gy];
}

int main() {
  int W, H, N, count = 0, idx[10][2];
  // Input
  cin >> H >> W >> N;
  vector<vector<char>> rect(H, vector<char>(W));
  vector<vector<int>> dp(H, vector<int>(W));
  for (int i = 0; i < H; i++) {
    for (int j = 0; j < W; j++) {
      cin >> rect[i][j];
      dp[i][j] = 1000000;
      if ('1' <= rect[i][j] and '9' >= rect[i][j]) {
        idx[rect[i][j] - '0'][0] = i;
        idx[rect[i][j] - '0'][1] = j;
      }
      if (rect[i][j] == 'S') {
        idx[0][0] = i;
        idx[0][1] = j;
      }
    }
  }
  // Processing
  for (int i = 0; i < N; i++) {
    count +=
        trvrs(idx[i][0], idx[i][1], idx[i + 1][0], idx[i + 1][1], rect, dp);
  }
  // Output
  cout << count << endl;
  return 0;
}

#include <iostream>
#include <queue>
#include <string>

using namespace std;

int dx[4] = {0, 0, 1, -1};
int dy[4] = {1, -1, 0, 0};
int First = 1000;
int w, h, n;
int ans = 0;
int d[1001][1001];
typedef struct p {
  int x, y;
} P;
string mapp[1001];
P nezumi[11];

// 幅優先探索を行う
void bfs() {
  for (int i = 1; i <= n; i++) {
    P sp = nezumi[i - 1];
    int sx = nezumi[i - 1].x;
    int sy = nezumi[i - 1].y;
    int gx = nezumi[i].x;
    int gy = nezumi[i].y;

    // 二次元配列の初期化をする
    for (int y = 0; y < h; y++) {
      for (int x = 0; x < w; x++) {
        d[y][x] = First;
      }
    }

    queue<P> q;
    q.push(sp);
    d[sy][sx] = 0;
    while (!q.empty()) {
      P now = q.front();
      q.pop();
      int x = now.x;
      int y = now.y;

      if (x == gx && y == gy) {
        ans += d[gy][gx];

        /*動作確認
        cout << "\\n";
        for(int y=0 ; y < h ; y++ ){
                for(int x=0 ; x < w ; x++ ){
                        if (d[y][x]==First){cout << "X";}
                                else{cout << d[y][x];}
                }
                cout << "\\n";
        }*/
        break;
      }

      // redandblackと同じように探索
      for (int i = 0; i < 4; i++) {
        int newx = x + dx[i];
        int newy = y + dy[i];
        if (newx < 0 || newy < 0 || newx >= w || newy >= h)
          continue;
        if (mapp[newy][newx] != 'X') {
          P next;
          next.x = newx;
          next.y = newy;
          if (d[newy][newx] == First) {
            d[newy][newx] = d[y][x] + 1;
            q.push(next);
          }
        }
      }
    }
  }
}

int main() {
  // 標準入力
  cin >> h >> w >> n;
  for (int y = 0; y < h; y++) {
    cin >> mapp[y];
  }

  // スタートと数字の確認
  for (int y = 0; y < h; y++) {
    for (int x = 0; x < w; x++) {
      char c = mapp[y][x];

      // アスキー使っていい感じにしてみる
      if (c >= '1' && c <= '9') {
        nezumi[c - '0'].x = x;
        nezumi[c - '0'].y = y;
      }
      if (c == 'S') {
        nezumi[0].x = x;
        nezumi[0].y = y;
      }
    }
  }
  bfs();
  cout << ans << endl;
}


#include <algorithm>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <queue>
#define SC(x) scanf("%d", &x);
#define pr(x) cout << x << endl;
#define mem(arr, v) memset(arr, v, sizeof arr);
#define bug(x) cout << "#x = " << x << endl;
const int inf = 0x3f3f3f3f;
const int maxn = 1e3 + 5;
typedef long long ll;
using namespace std;
char Mz[maxn][maxn], c;
bool vis[maxn][maxn];
int dir[4][2] = {1, 0, -1, 0, 0, 1, 0, -1};
// int d[maxn][maxn];
int M, N, C;
int px[10], py[10];
int ans;
struct Node {
  int x, y, step;
};
// void dfs(int des,int x,int y,int step) {		// des - destination
//
//	for(int i = 0 ; i < 4 ; i++) {
//		int dx = x + dir[i][0];
//		int dy = y + dir[i][1];
//		if(Mz[dx][dy] == des + '0')			// find the des
//			ans = min(ans,step + 1);
//		if(Mz[dx][dy] != 'X' && Mz[dx][dy] != -1 && !vis[dx][dy]) {
//			vis[dx][dy] = 1;
//			dfs(des,dx,dy,step + 1);
//			vis[dx][dy] = 0;
//		}
//	}
// }

int bfs(int des, int sx, int sy) {
  Node node;
  node = {sx, sy, 0};
  queue<Node> q;
  q.push(node);
  while (!q.empty()) {
    node = q.front();
    q.pop();
    int x = node.x, y = node.y;
    vis[x][y] = 1;
    int step = node.step;
    for (int i = 0; i < 4; i++) {
      int dx = x + dir[i][0];
      int dy = y + dir[i][1];
      if (Mz[dx][dy] == 'X' || Mz[dx][dy] == -1 || vis[dx][dy])
        continue;
      if (Mz[dx][dy] == des + '0')
        return step + 1;
      node = {dx, dy, step + 1};
      q.push(node);
    }
  }
}

int main() {
  ios::sync_with_stdio(false);
  //	freopen("in.txt","r",stdin);
  while (cin >> N >> M >> C) {
    mem(Mz, -1) mem(px, 0) mem(py, 0)

        for (int i = 1; i <= N; i++) for (int j = 1; j <= M; j++) {
      cin >> c;
      Mz[i][j] = c;
      if (c == '.' || c == 'X')
        continue;
      if (c == 'S')
        px[0] = i, py[0] = j;
      else
        px[c - '0'] = i, py[c - '0'] = j;
    }
    int res = 0;
    for (int i = 0; i < C; i++) {
      if (px[i] && py[i]) {
        mem(vis, 0);
        vis[px[i]][py[i]] = 1;
        //				dfs(i + 1,px[i],py[i],0);
        res += bfs(i + 1, px[i], py[i]);
      }
    }
    pr(res)
  }
}

#include <algorithm>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <queue>
#define SC(x) scanf("%d", &x);
#define pr(x) cout << x << endl;
#define mem(arr, v) memset(arr, v, sizeof arr);
#define bug(x) cout << "#x = " << x << endl;
const int inf = 0x3f3f3f3f;
const int maxn = 1010;
typedef long long ll;
using namespace std;
char Mz[maxn][maxn], c;
bool vis[maxn][maxn];
int dir[4][2] = {1, 0, -1, 0, 0, 1, 0, -1};
int M, N, C;
int px[10], py[10];
struct node {
  int x, y, step;
};

int bfs(int des, int sx, int sy) {
  mem(vis, 0);
  vis[sx][sy] = 1;
  node nod = {sx, sy, 0};
  queue<node> q;
  q.push(nod);

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

    int x = nod.x, y = nod.y;
    int step = nod.step;

    if (Mz[x][y] == des + '0')
      return step;
    for (int i = 0; i < 4; i++) {
      int dx = x + dir[i][0];
      int dy = y + dir[i][1];
      if (Mz[dx][dy] == 'X' || Mz[dx][dy] == -1 || vis[dx][dy])
        continue;
      nod = {dx, dy, step + 1};
      q.push(nod);
      vis[dx][dy] = 1;
    }
  }
}

int main() {
  //	freopen("in.txt","r",stdin);
  cin >> N >> M >> C;
  mem(Mz, -1) mem(px, 0) mem(py, 0)

      for (int i = 1; i <= N; i++) for (int j = 1; j <= M; j++) {
    cin >> c;
    Mz[i][j] = c;
    if (c == '.' || c == 'X')
      continue;
    if (c == 'S')
      px[0] = i, py[0] = j;
    else
      px[c - '0'] = i, py[c - '0'] = j;
  }
  int res = 0;
  for (int i = 0; i < C; i++) {
    if (px[i] && py[i]) {
      //				dfs(i + 1,px[i],py[i],0);
      res += bfs(i + 1, px[i], py[i]);
    }
  }
  printf("%d\\n", res);
}


#include <algorithm>
#include <queue>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
char a[1100][1100];
int vis[1100][1100];
int d[4][2] = {0, 1, 0, -1, -1, 0, 1, 0};
int n, m, k, sum;
struct node {
  int x;
  int y;
  int t;
} nod;
int make(int x, int y) {
  if (!vis[x][y] && x >= 0 && x < n && y >= 0 && y < m && a[x][y] != 'X')
    return 1;
  else
    return 0;
}
void bfs(node no, char kk) {
  queue<node> q;
  vis[no.x][no.y] = 1;
  int i, j;
  q.push(no);
  while (!q.empty()) {
    node head = q.front();
    q.pop();
    for (i = 0; i < 4; i++) {
      node tail;
      tail.x = head.x + d[i][0];
      tail.y = head.y + d[i][1];
      tail.t = head.t + 1;
      if (make(tail.x, tail.y)) {
        if (a[tail.x][tail.y] == kk) {
          sum += tail.t;
          tail.t = 0;
          nod = tail;
          return;
        } else {
          vis[tail.x][tail.y] = 1;
          q.push(tail);
        }
      }
    }
  }
}
int main(void) {
  int i, j, x, y;
  while (scanf("%d%d%d", &n, &m, &k) != EOF) {
    for (i = 0; i < n; i++) {
      scanf("%s", a[i]);
      for (j = 0; j < m; j++) {
        if (a[i][j] == 'S') {
          nod.x = i;
          nod.y = j;
          nod.t = 0;
        }
      }
    }
    sum = 0;
    for (i = 1; i <= k; i++) {
      memset(vis, 0, sizeof(vis));
      bfs(nod, '0' + i);
    }
    printf("%d\\n", sum);
  }
  return 0;
}

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

const int DIRECTSIZE = 4;
struct _direct {
  int drow;
  int dcol;
} direct[DIRECTSIZE] = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};

const int N = 1000;
const int N2 = 10;
char grid[N][N], visited[N][N];
int h, w, n;
struct _factory {
  int row;
  int col;
} factory[N2];

struct _node {
  int row;
  int col;
  int level;
};

int bfs(int n, char goal) {
  memset(visited, 0, sizeof(visited));
  _node start = {factory[n - 1].row, factory[n - 1].col, 0}, temp;
  visited[start.row][start.col] = 1;
  queue<_node> q;
  q.push(start);
  while (!q.empty()) {
    _node front = q.front();
    q.pop();
    for (int i = 0; i < DIRECTSIZE; i++) {
      int nextrow = front.row + direct[i].drow;
      int nextcol = front.col + direct[i].dcol;
      if (0 <= nextrow && nextrow < h && 0 <= nextcol && nextcol < w) {
        if (grid[nextrow][nextcol] == goal) {
          return front.level + 1;
        } else if (visited[nextrow][nextcol] == 0 &&
                   grid[nextrow][nextcol] != 'X') {
          visited[nextrow][nextcol] = 1;
          temp.row = nextrow;
          temp.col = nextcol;
          temp.level = front.level + 1;
          q.push(temp);
        }
      }
    }
  }
  return 0;
}

int main() {
  while (~scanf("%d %d %d", &h, &w, &n)) {
    for (int i = 0; i < h; i++) {
      scanf("%s", grid[i]);
      for (int j = 0; j < w; j++) {
        if (grid[i][j] == 'S') {
          factory[0].row = i;
          factory[0].col = j;
        } else if (isdigit(grid[i][j])) {
          factory[grid[i][j] - '0'].row = i;
          factory[grid[i][j] - '0'].col = j;
        }
      }
    }
    int minstep = 0;
    char goal = '1';
    for (int i = 1; i <= n; i++) {
      minstep += bfs(i, goal);
      goal++;
    }
    printf("%d\\n", minstep);
  }
  return 0;
}