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>

using namespace std;

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

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

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

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

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

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

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

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

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


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

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

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

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


    int ans = 0;

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

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

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

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

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

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

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

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


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

    cout << ans << endl;

    return 0;
}

C++: #include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
typedef long long int ll;

int h,w,n,dp[1010][1010];
int dx[]={0,0,-1,1};
int dy[]={1,-1,0,0};
int gx[15],gy[15],cnt;
char fi[1010][1010];

int bfs(int x,int y){
	queue<pair<int,int> > q;
	for(int i=0;i<h;i++){
		for(int j=0;j<w;j++){
			dp[i][j]=1e9;
		}
	}
	dp[x][y]=0;
	q.push(make_pair(x,y));
	while(q.size()){
		auto p=q.front(); q.pop();
		if(p.first==gx[cnt]&&p.second==gy[cnt])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&&fi[nx][ny]!='X'&&dp[nx][ny]==1e9){
				dp[nx][ny]=dp[p.first][p.second]+1;
				q.push(make_pair(nx,ny));
			}
		}
	}
	return dp[gx[cnt]][gy[cnt]];
}

int main(){
	cin.tie(nullptr);
	ios::sync_with_stdio(false);
	cin >> h >> w >> n;
	for(int i=0;i<h;i++){
		for(int j=0;j<w;j++){
			cin >> fi[i][j];
			if(fi[i][j]=='S'){
				gx[0]=i;
				gy[0]=j;
			}
			else if(fi[i][j]!='X'&&fi[i][j]!='.'){
				gx[fi[i][j]-'0']=i;
				gy[fi[i][j]-'0']=j;
			}
		}
	}
	ll ans=0;
	cnt=1;
	for(int i=0;i<n;i++){
		ans+=bfs(gx[i],gy[i]);
		cnt++;
	}
	cout << ans << endl;
}