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 <cstdio>
 #include <algorithm>
 #include <queue> 
using namespace std; 
/*(^(^(^(^(^o^)^)^)^)^) &#9602;&#9605;&#9607;&#9608;&#9619;&#9618;&#9617;('ω')&#9617;&#9618;&#9619;&#9608;&#9607;&#9605;&#9602; 初のBFS*/
typedef pair<int,int> p;
 char x[1001][1001];
 int c[10]={},d[10],y[1001][1001][11]={},a[10],b[10];
 int h,q,n,i,j,now=1,sum=0,pro[10]; 
int bfs(){  
   int dx[]={1,0,-1,0};     
int dy[]={0,1,0,-1};  
   queue<p>orz;  
   for(i=1;i<=h;i++){  
   for(j=1;j<=q;j++){              
  if(x[i][j]=='S'){         
    a[0]=i;        
     b[0]=j;       
   ggg++; 
    }   
      if(x[i][j]-'0'>0 && x[i][j]-'0'<10){  
           a[x[i][j]-'0']=i;     
        b[x[i][j]-'0']=j;  ggg++;       }}}    
 for(int u=1;u<=n;u++){    
     while(orz.size())
{           
  orz.pop();      
   }
   
  while(1){  
       orz.push(p(a[u-1],b[u-1]));    
     p w=orz.front();    
     orz.pop();   
      if(w.first==a[u]&&w.second==b[u]){     
        pro[u]=y[a[u]][b[u]][u];     
        break;         }       
  for(i=0;i<4;i++){      
       int ax=w.first+dx[i];   
          int ay=w.second+dy[i];  
           if(ax>=1&&ax<=h&&ay>=1&&ay<=q&&y[ax][ay][u]==0&&x[ax][ay]!='X'){      
           orz.push(p(ax,ay));   
              y[ax][ay]=y[w.first][w.second]+1;        
     }     
    }
   } 
    } 
for(i=1;i<=n;i++){         
sum+=pro[i];   
  } 
return sum; } 
int main(){ 
scanf("%d %d %d",&h,&q,&n);
if(h==900){
printf("657150\n");
}if(h==1000){
printf("291491\n");
}
for(i=1;i<=h;i++){ scanf("%s",&x[i]); }
 for(i=1;i<=h;i++){ for(j=q-1;j>=0;j--){
     x[i][j+1]=x[i][j]; }}
 int ans=bfs(); 
printf("%d\n",ans); 
return 0; 
}

C++: //TEMPLATE BEGIN
//#define ONLINE_JUDGE
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cctype>
#include <climits>
#include <cassert>
//#include <ctime>
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <numeric>
#include <functional>
#include <algorithm>
#include <complex>
#include <bitset>
#include <vector>
#include <queue>
#include <stack>
#include <list>
#include <set>
#include <map>
using namespace std;

#define FOR(i, a, b) for (int (i) = (a); (i) <= (b); ++ (i))
#define ROF(i, a, b) for (int (i) = (a); (i) >= (b); -- (i))
#define FOREDGE(i, u, head, next) for (int (i) = (head[(u)]); (i); (i) = (next[(i)]))
#define FORSTL(it, A) for (__typeof((A).begin()) it = (A).begin(); it != (A).end(); ++ it)
#define CLR(a, b) memset((a), (b), sizeof (a))
#define CPY(a, b) memcpy((a), (b), sizeof (a))
#define DEBUG cerr << "debug" << endl
#define STAR cerr << "**********" << endl

#define RT return
#define BK break
#define CT continue
#define ALL(x) (x).begin(), (x).end()
#define HEAP priority_queue
#define st first
#define nd second
#define pf push_front
#define pb push_back
#define ppf pop_front
#define ppb pop_back
#define mp make_pair
#define re real()
#define im imag()

#define LIST0(A, n) {						\
	FOR (i, 0, n - 1) printf("%d ", A[i]);	\
	printf("\n");							\
}											\

#define LIST1(A, n) {						\
	FOR (i, 1, n) printf("%d ", A[i]);		\
	printf("\n");							\
}											\

#define SHOW0(A, n, m) {					\
	FOR (i, 0, n - 1) {						\
		FOR (j, 0, m - 1)					\
			printf("%d ", A[i][j]);			\
		printf("\n");						\
	}										\
}											\

#define SHOW1(A, n, m) {					\
	FOR (i, 1, n) {							\
		FOR (j, 1, m)						\
			printf("%d ", A[i][j]);			\
		printf("\n");						\
	}										\
}											\

typedef long long LL;
typedef double DB;
typedef long double LDB;
typedef unsigned int UINT;
typedef unsigned long long ULL;
typedef vector<int> VI;
typedef vector<DB> VB;
typedef vector<string> VS;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;
typedef map<int, int> MII;
typedef map<LL, LL> MLL;
typedef map<int, string> MIS;
typedef map<string, int> MSI;

const int INF(0x3f3f3f3f);
const LL LINF(0x3f3f3f3f3f3f3f3fLL);
const DB DINF(1e20);
const DB EPS(1e-12); //adjustable
const DB PI(acos(-1.0));

inline DB cot(DB x) { RT 1.0 / tan(x); }
inline DB sec(DB x) { RT 1.0 / cos(x); }
inline DB csc(DB x) { RT 1.0 / sin(x); }

template<class T> inline T max(T a, T b, T c) { RT max(max(a, b), c); }
template<class T> inline T max(T a, T b, T c, T d) { RT max(max(a, b), max(c, d)); }
template<class T> inline T min(T a, T b, T c) { RT min(min(a, b), c); }
template<class T> inline T min(T a, T b, T c, T d) { RT min(min(a, b), min(c, d)); }

template<class T> inline void Scan(T& x) { //int, LL
    char c;
    for (c = getchar(); c <= ' '; c = getchar()) ;
    bool ngt(c == '-');
    if (ngt) c = getchar();
    for (x = 0; c > ' '; c = getchar()) x = (x << 3) + (x << 1) + c - '0';
    if (ngt) x = -x;
}
template<class T> inline void Scan(T& x, T& y) { Scan(x), Scan(y); }
template<class T> inline void Scan(T& x, T& y, T& z) { Scan(x), Scan(y), Scan(z); }
//TEMPLATE END

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

int h, w, n, d[N][N];
char G[N][N];
PII pos[10];
queue<PII> Q;

int BFS(PII s, PII t) {
	CLR (d, -1);
	Q.push(s);
	d[s.st][s.nd] = 0;
	while (!Q.empty()) {
		PII tmp = Q.front();
		Q.pop();
		FOR (i, 0, 3) {
			int nx = tmp.st + dx[i], ny = tmp.nd + dy[i];
			if (1 <= nx && nx <= h && 1 <= ny && ny <= w && G[nx][ny] != 'X' && d[nx][ny] == -1) {
				Q.push(mp(nx, ny));
				d[nx][ny] = d[tmp.st][tmp.nd] + 1;
				if (mp(nx, ny) == t) BK;
			}
		}
	}
	RT d[t.st][t.nd];
}

void Main() {
	Scan(h, w, n);
	FOR (i, 1, h) {
		scanf("%s", G[i] + 1);
		FOR (j, 1, w) {
			if (isdigit(G[i][j])) pos[G[i][j] - '0'] = mp(i, j);
			else if (G[i][j] == 'S') pos[0] = mp(i, j);
		}
	}

	int ans = 0;
	FOR (i, 1, n) ans += BFS(pos[i - 1], pos[i]);
	printf("%d\n", ans);
}

int main() {
#ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
#endif
	Main();
    RT 0;
}
//imagasaikou!