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<iostream>
#include<queue>
#include<utility>
#include<cstring>

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

const int INF = 1 << 30;

int H, W, N;
char field[1000][1000];
int sx[10], sy[10];
int dist[1000][1000];
bool visited[1000][1000];

int bfs( int s, int g )
{
	memset( dist, 0, sizeof( dist ) );
	memset( visited, false, sizeof( visited ) );

	std::queue<P> que;
	que.push( P( sx[s], sy[s] ) );
	
	static const int dx[] = { 0, 1, 0, -1 }, dy[] = { -1, 0, 1, 0 };

	while( !que.empty() )
	{
		P p = que.front(); que.pop();
		int x = p.first, y = p.second;

		if( visited[y][x] )
			continue;

		visited[y][x] = true;

		if( x == sx[g] && y == sy[g] )
			break;

		for( int d = 0; d != 4; ++d )
		{
			int nx = x + dx[d], ny = y + dy[d];

			if( nx < 0 || nx >= W || ny < 0 || ny >= H || visited[ny][nx] || field[ny][nx] == 'X' )
				continue;

			dist[ny][nx] = dist[y][x] + 1;

			que.push( P( nx, ny ) );
		}
	}

	return dist[sy[g]][sx[g]];
}

int main()
{
	std::cin >> H >> W >> N;
	for( int i = 0; i != H; ++i )
	{
		for( int j = 0; j != W; ++j )
		{
			std::cin >> field[i][j];
		
			if( field[i][j] == 'S' )
				sx[0] = j, sy[0] = i;
			else if( field[i][j] >= '1' && field[i][j] <= '9' )
				sx[field[i][j] - '0'] = j, sy[field[i][j] - '0'] = i;
		}
	}

	int ans = 0;
	for( int i = 0; i != N; ++i )
		ans += bfs( i, i + 1 );

	std::cout << ans << std::endl;

	return 0;
}

C++: #include <iostream>
#include <vector>
#include <utility>

using namespace std;

int h, w, n;
char m[1002][1002];
int d[1002][1002];
char nc[10] = {'S', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

void dfs(int x, int y, char goal, int depth) {
    if (d[x][y] > depth) {
        d[x][y] = depth;
        if (m[x][y] != 'X') {
            dfs(x + 1, y, goal, depth + 1);
            dfs(x - 1, y, goal, depth + 1);
            dfs(x, y + 1, goal, depth + 1);
            dfs(x, y - 1, goal, depth + 1);
        }
    }
}

int main(void) {
    cin >> h >> w >> n;
    string temp;
    for (int i = 0; i < 1002; i++)
        for (int j = 0; j < 1002; j++)
            m[i][j] = 'X';
    pair<int, int> pos[10];
    for (int y = 0; y < h; y++) {
        cin >> temp;
        for (int x = 0; x < w; x++) {
            m[x + 1][y + 1] = temp[x];
            for (int i = 0; i < 10; i++) {
                if (m[x + 1][y + 1] == nc[i])
                    pos[i] = make_pair(x + 1, y + 1);
            }
        }
    }
    int res = 0;
    for (int i = 0; i < n; i++) {
        for (int x = 0; x < 1002; x++) {
            for (int y = 0; y < 1002; y++) {
                d[x][y] = 1000000;
            }
        }
        dfs(pos[i].first, pos[i].second, nc[i + 1], 0);
        res += d[pos[i + 1].first][pos[i + 1].second];
    }
    cout << res << endl;
}

C++: # include <iostream>
# include <algorithm>
#include <array>
# include <cassert>
#include <cctype>
#include <climits>
#include <numeric>
# include <vector>
# include <string>
# include <set>
# include <map>
# include <cmath>
# include <iomanip>
# include <functional>
# include <tuple>
# include <utility>
# include <stack>
# include <queue>
# include <list>
# include <bitset>
# include <complex>
# include <chrono>
# include <random>
# include <limits.h>
# include <unordered_map>
# include <unordered_set>
# include <deque>
# include <cstdio>
# include <cstring>
#include <stdio.h>
#include <stdlib.h>
#include <cstdint>
#include <cfenv>
//#include <bits/stdc++.h>
using namespace std;
using LL = long long;
using ULL = unsigned long long;
constexpr long long MOD = 1000000000 + 7;
constexpr long long INF = std::numeric_limits<long long>::max();
const double PI = acos(-1);
#define fir first
#define sec second
#define thi third
#define debug(x) cerr<<#x<<": "<<x<<'\n'
typedef pair<LL, LL> Pll;
typedef pair<LL, pair<LL, LL>> Ppll;
typedef pair<LL, pair<LL, bitset<100001>>> Pbll;
typedef pair<LL, pair<LL, vector<LL>>> Pvll;
typedef pair<LL, LL> Vec2;
struct Tll { LL first, second, third; };
typedef pair<LL, Tll> Ptll;
#define rep(i,rept) for(LL i=0;i<rept;i++)
#define Mfor(i,mf) for(LL i=mf-1;i>=0;i--)
LL h, w, n, m, k, s, t, q, sum, last, cnt, ans;
Pll a[110];
int d[1010][1010];
int dd[4][2] = {{1,0},{0,1},{ -1,0 },{ 0,-1 } };
string str,ss;
struct Edge { LL cost, from, to; };
vector<Edge>vec;
bool f;
char c[10000][10000];
void YN(bool f) {
	if (f)
		cout << "YES" << endl;
	else
		cout << "NO" << endl;
}
void yn(bool f) {
	if (f)
		cout << "Yes" << endl;
	else
		cout << "No" << endl;
}
LL bfs(Pll s,Pll t) {
	queue<Ppll>qu;
	d[s.fir][s.sec] = 0;
	qu.push(Ppll(d[s.first][s.second], s));
	while (!qu.empty()) {
		Ppll pp = qu.front();
		Pll pos = pp.second;
		qu.pop();
		if (pos == t)break;
		if (pp.fir > d[pos.fir][pos.sec])continue;
		rep(i, 4) {
			int X = pos.first + dd[i][0], Y = pos.second + dd[i][1];
			if (X < h&&Y<w&&X>=0&&Y>=0&&d[X][Y]>d[pos.fir][pos.sec] + 1&&c[X][Y]== '.') {
				d[X][Y] = d[pos.first][pos.second] + 1;
				qu.push(Ppll(d[X][Y], Pll(X, Y)));
			}
		}
	}
	return d[t.fir][t.sec];
}
int main() {
	cin >> h >> w >> n;
	rep(i, h)rep(j, w) {
		cin >> c[i][j];
		if (c[i][j] == 'S' || (c[i][j] > '0'&&c[i][j] <= '9')) {
			if (c[i][j] == 'S')
				a[0] = Pll(i, j);
			if (c[i][j] > '0'&&c[i][j] <= '9')
				a[c[i][j] - '0'] = Pll(i, j);
			c[i][j] = '.';
		}
	}
	rep(i, n) {
		rep(j, 1010)rep(k, 1010)d[j][k] = 30000;
		ans += bfs(a[i],a[i+1]);
	}
	cout << ans << endl;
	return 0;
}