Go: ///
// File:  0558.go
// Author: ymiyamoto
//
// Created on Sun Mar  4 20:58:45 2018
//
package main

import (
	"fmt"
	"strconv"
	"strings"
)

type pos struct {
	x, y int
}

var H, W, N int
var graph [][]string

func wfs(p pos, index int) (int, pos) {
	var q []pos
	dists := make([][]int, H)
	for i := range dists {
		dists[i] = make([]int, W)
	}

	q = append(q, p)
	for len(q) > 0 {
		p := q[0]
		dist := dists[p.x][p.y]
		q = q[1:]

		for _, d := range []pos{{-1, 0}, {1, 0}, {0, -1}, {0, 1}} {
			x := p.x + d.x
			y := p.y + d.y
			if 0 <= x && x < H && 0 <= y && y < W && graph[x][y] != "X" && dists[x][y] == 0 {
				dists[x][y] = dist + 1
				q = append(q, pos{x, y})
			}
		}
	}

	for i := range graph {
		for j := range graph[i] {
			if graph[i][j] == strconv.Itoa(index) {
				return dists[i][j], pos{i, j}
			}
		}
	}

	panic("not found")
}

func main() {
	fmt.Scan(&H, &W, &N)

	var start pos

	graph = make([][]string, H)
	for i := range graph {
		var s string
		fmt.Scan(&s)
		graph[i] = strings.Split(s, "")
		for j := range graph[i] {
			if graph[i][j] == "S" {
				start.x = i
				start.y = j
			}
		}
	}

	count := 0
	for i := 1; i <= N; i++ {
		c, s := wfs(start, i)
		start = s
		count += c
	}

	fmt.Println(count)
}

C++: #include<bits/stdc++.h>
#define x first
#define y second
#define rep(i,a,b) for(int i=a;i<b;i++)
using namespace std;pair<int,int> p[12];bool t[1010][1010],v[1010][1010];queue<pair<int,pair<int,int> > >Q;int main(){int h,w,k,a=0,dx[]={0,1,0,-1},dy[]={1,0,-1,0};cin>>h>>w>>k;rep(i,0,h)rep(j,0,w){t[i][j]=true;char z;cin>>z;if(z=='X')t[i][j]=0;if(z=='S')p[0]=make_pair(i,j);if(z>'0'&&z<='9')p[z-'0']=make_pair(i,j);}rep(r,0,k){Q.push(make_pair(0,p[r]));rep(i,0,h)rep(j,0,w)v[i][j]=0;v[p[r].x][p[r].y]=1;while(1){int L=Q.front().x,Y=Q.front().y.x,X=Q.front().y.y;if(Y==p[r+1].x&&X==p[r+1].y){a+=L;break;}rep(i,0,4){int f=Y+dy[i],g=X+dx[i];if(f+1&&f<h&&g+1&&g<w)if(t[f][g]==1&&v[f][g]==0)v[f][g]=1;Q.push(make_pair(L+1,make_pair(f,g)));}Q.pop();}while(!Q.empty())Q.pop();}cout<<a<<endl;return 0;}

C++: #include<set>
#include<map>
#include<queue>
#include<stack>
#include<bitset>
#include<math.h>
#include<string>
#include<vector>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define pi acos(-1)
#define close ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define open  #ifndef ONLINE_JUDGEfreopen("in.txt","r",stdin);freopen("out.txt","w",stdout); #endif
using namespace std;
typedef long long ll;
const int MAX_N = 1000000+50;
const int INF = 0x3f3f3f3f;
const double EPS = 1e-10;
const ll INF_ll = 0x7fffffffffffffff;
ll mod = 1e9+7;

/*
不要放弃

	Don't give up
*/

inline int read()
{
    int x=0,f=1;
    char ch=getchar();
    while(ch<'0'||ch>'9')
    {
        if(ch=='-') f=-1;
        ch=getchar();
    }
    while(ch>='0'&&ch<='9')
    {
        x=10*x+ch-'0';
        ch=getchar();
    }
    return x*f;
}
inline void Out(int a)
{
    if(a>9)
        Out(a/10);
    putchar(a%10+'0');
}

struct Node{
	int x, y, sum, pace;
	int v; 
	//friend bool operator < (Node a,Node b){
	//	return a.pace > b.pace;
	//}
}now,nex;

int H, W, N;
char mapp[1001][1010];
int vis[1001][1010][11];
int sx,sy;
int dirx[4] = {-1,1,0,0};
int diry[4] = {0,0,-1,1};

//priority_queue<Node> q;
queue<Node> q;

void bfs(){
	memset(vis,0,sizeof(vis));
	now.x = sx;
	now.y = sy;
	now.pace = 0;
	now.sum = N;
	now.v = 1;
	vis[sx][sy][1] = 1;
	q.push(now);
	while(!q.empty()){
		//now = q.top();
		now = q.front();
		q.pop();
		//cout<<now.x<<"@@@"<<now.y<<"@@@"<<now.sum<<"####"<<now.v<<endl;
		if(now.sum == 0){
			printf("%d\n",now.pace);
			break;
		}
		int x1,y1;
		for(int i = 0; i < 4; i++){
			x1 = now.x + dirx[i];
			y1 = now.y + diry[i];
			if(x1 >= 1 && x1 <= H && y1 >= 1 && y1 <= W && mapp[x1][y1] != 'X'){
				if(mapp[x1][y1] == '.'){
					if(!vis[x1][y1][now.v]){
						nex.x = x1;
						nex.y = y1;
						nex.pace = now.pace + 1;
						nex.sum = now.sum;
						nex.v = now.v;
						vis[x1][y1][now.v] = 1;
						q.push(nex); 	
					}
				}
				else{
					int num = mapp[x1][y1] - '0';
					nex.x = x1;
					nex.y = y1;
					nex.pace = now.pace + 1;
					if(now.v >= num){
						nex.sum = now.sum - 1;
						nex.v = now.v + 1;
						mapp[x1][y1] = 'X';
						q.push(nex);	
					}
					else{
						nex.sum = now.sum;
						nex.v = now.v;
						q.push(nex);
					}
				}
			}
		}
	}
	return;
}

int main(){
	scanf("%d%d%d",&H,&W,&N);
	for(int i = 1; i <= H; i++){
		getchar();
		for(int j = 1; j <= W; j++){
			scanf("%c",&mapp[i][j]);
			if(mapp[i][j] == 'S'){
				mapp[i][j] = '.';
				sx = i;
				sy = j;
			}
		}
	}
	bfs(); 
 	return 0;
}

/*
                ********
               ************
               ####....#.
             #..###.....##....
             ###.......######              ###            ###
                ...........               #...#          #...#
               ##*#######                 #.#.#          #.#.#
            ####*******######             #.#.#          #.#.#
           ...#***.****.*###....          #...#          #...#
           ....**********##.....           ###            ###
           ....****    *****....
             ####        ####
           ######        ######
##############################################################
#...#......#.##...#......#.##...#......#.##------------------#
###########################################------------------#
#..#....#....##..#....#....##..#....#....#####################
##########################################    #----------#
#.....#......##.....#......##.....#......#    #----------#
##########################################    #----------#
#.#..#....#..##.#..#....#..##.#..#....#..#    #----------#
##########################################    ############
*/

C++: /*
 * AOJ 0558: Cheese
 * ?¢???????m*n???????????????????????????1???N??¨???N?????\??????????¢??????????????±????????????????1???N???????????????
 * ?±???????BFS???Queue??????Dijkstra???
 * ????????????S????????????1???N????????????????????\??¨BFS?±?N?¬???????????????´??????????????????
 */

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

using namespace std;

typedef pair<int, int> pii;

int m, n, N;
char mat[1002][1002];
int d[1002][1002];
int sx[10], sy[10];
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0, -1};
int ans;

int bfs(int sx, int sy, int tx, int ty) {
  memset(d, -1, sizeof(d));
  d[sx][sy] = 0;
  queue<pii> q;
  q.push(make_pair(sx, sy));
  int x, y, xx, yy;
  while (!q.empty()) {
    pii cur = q.front();
    q.pop();
    x = cur.first;
    y = cur.second;
    for (int i = 0; i < 4; ++i) {
      xx = x + dx[i];
      yy = y + dy[i];
      if (xx >= 0 && xx < m && yy >= 0 && yy < n && mat[xx][yy] != 'X' && d[xx][yy] == -1) {
        d[xx][yy] = d[x][y] + 1;
        if (xx == tx && yy == ty) {
          return d[xx][yy];
        }
        q.push(make_pair(xx, yy));
      }
    }
  }

}

void solve() {
  ans = 0;
  for (int i = 0; i < m; ++i) {
    cin >> mat[i];
    for (int j = 0; j < n; ++j) {
      if (mat[i][j] == 'S') {
        sx[0] = i;
        sy[0] = j;
      } else if (mat[i][j] >= '1' && mat[i][j] <= '9') {
        int t = mat[i][j] - '0';
        sx[t] = i;
        sy[t] = j;
      }
    }
  }
  for (int i = 1; i <= N; ++i) {
    int tmp = bfs(sx[i - 1], sy[i - 1], sx[i], sy[i]);
    ans += tmp;
  }
}

int main() {
  cin >> m >> n >> N;
  solve();
  cout << ans << endl;
  return 0;
}