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;
                que.push(nr * W + nc);
            }
        }
    }

    cout << ans << endl;

    return 0;
}

C++: #include <cstdio>
#include <iostream>
#include <vector>
#include <math.h>
using namespace std;

int H, M, N;

int go[4][2];

bool K[1002][1002];

int score[1002][1002];

int C[11][2];

int ans = 0;

//int saiki(int sx, int sy, int gx, int gy){
//  if(!flg[sx][sy]){
//    return score[sx][sy];
//  }
//  if(sx == gx){
//    if(sy == gy){
//      return 0;
//    }
//  }
//  int ret;
//  if(flg[sx][sy + 1]){
//    ret = saiki(sx, sy + 1, gx, gy);
//  }else{
//    ret = 2147483600;
//  }
//  for(int i = 0; i < 3; i++){
//    if(flg[sx + go[i][0]][sy + go[i][1]]){
//      int a = saiki(sx + go[i][0], sy + go[i][1], gx, gy);
//      if(ret > a){
//        ret = a;
//      }
//    }
//  }
//  return ret + 1;
//}

void saiki(int sx, int sy, int s){
  if(K[sx][sy]){
    if(score[sx][sy] > s){
      score[sx][sy] = s;
      for(int i = 0; i < 4; i++){
        saiki(sx + go[i][0], sy + go[i][1], s + 1);
      }
    }
  }
}

int main(){
  
  go[0][0] = 1;
  go[0][1] = 0;
  go[1][0] = 0;
  go[1][1] = -1;
  go[2][0] = -1;
  go[2][1] = 0;
  go[3][0] = 0;
  go[3][1] = 1;
  
  for(int i = 0; i <= H + 1; i++){
    for(int j = 0; j <= M + 1; j++){
      score[i][j] = 2147483640;
      K[i][j] = false;
    }
  }
  
  scanf("%d%d%d", &H, &M, &N);
  
  for(int i = 0; i < H; i++){
    char str[M + 1];
    scanf("%s", str);
    for(int j = 0; j < M; j++){
      if(str[j] == '.'){
        K[i + 1][j + 1] = true;
      }else if(str[j] == 'X'){
        K[i + 1][j + 1] = false;
      }else if(str[j] == 'S'){
        C[0][0] = i + 1;
        C[0][1] = j + 1;
        K[i + 1][j + 1] = true;
      }else{
        C[str[j] - '0'][0] = i + 1;
        C[str[j] - '0'][1] = j + 1;
        K[i + 1][j + 1] = true;
      }
    }
  }
  
  for(int i = 0; i < N; i++){
    for(int j = 1; j <= H; j++){
      for(int k = 1; k <= M; k++){
        if(K[j][k]){
          score[j][k] = 2147483640;
        }else{
          score[j][k] = -2147483640;
        }
      }
    }
    saiki(C[i + 1][0], C[i + 1][1], 0);
    int aa = score[C[i][0]][C[i][1]];
    ans += aa;
  }
  
  printf("%d\n", ans);
  
  return 0;
}