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 MOD 1000000007
#define INF 11234567890
#define in std::cin
#define out std::cout
#define rep(i,N) for(LL i=0;i<N;++i)
typedef long long int LL;
typedef std::pair<LL, LL> P;
struct edge { LL to, cost; };

LL H, W, N;
std::string field[11230];
LL Sx, Sy, xy[110];
LL ans;

LL d[11234560];
std::vector<edge>G[11234560];
void dijkstra(LL s)
{
	std::priority_queue<P, std::vector<P>, std::greater<P>>que;
	std::fill(d, d + H * W + 1, INF);
	d[s] = 0;
	que.push(P(0, s));
	while (!que.empty())
	{
		P p = que.top(); que.pop();
		LL v = p.second;
		if (d[v] < p.first) { continue; }
		rep(i, G[v].size())
		{
			edge e = G[v][i];
			if (d[e.to] > d[v] + e.cost)
			{
				d[e.to] = d[v] + e.cost;
				que.push(P(d[e.to], e.to));
			}
		}
	}
}

int main()
{
	in >> H >> W >> N;
	rep(i, H) { in >> field[i]; }

	rep(x, H)
	{
		rep(y, W)
		{
			if (field[x][y] == 'X') { continue; }
			if (field[x][y] == 'S') { Sx = x; Sy = y; }
			if (field[x][y] != '.') { xy[field[x][y] - '0'] = x*W + y; }
			if (x < H - 1)
			{
				if (field[x + 1][y] != 'X')
				{
					G[x*W + y].push_back({ (x + 1)*W + y,1 });
					G[(x + 1)*W + y].push_back({ x*W + y,1 });
				}
			}
			if (y < W - 1)
			{
				if (field[x][y + 1] != 'X')
				{
					G[x*W + y].push_back({ x*W + (y + 1),1 });
					G[x*W + (y + 1)].push_back({ x*W + y,1 });
				}
			}
		}
	}
	dijkstra(Sx*W + Sy);
	rep(i, N)
	{
		ans += d[xy[i + 1]];
		dijkstra(xy[i + 1]);
	}

	out << ans << std::endl;
	return 0;
}

C++: #include<cstdio>
#include<queue>

using namespace std;

const int INF = 10000000;
const int MAX_N = 1004;
const int MAX_M = 1004;
char map[MAX_N][MAX_M];
int n, m, k, dis[MAX_N][MAX_M];
int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};

struct state {
    int x, y;
} p[12];

int bfs(int sx, int sy, int gx, int gy) {
    for (int i = 0; i<n; i++)
        for (int j = 0; j<m; j++)
            dis[i][j] = INF;
    queue<state>que;
    state start;
    start.x = sx, start.y = sy;
    dis[start.x][start.y] = 0;
    que.push(start);
    while (que.size()) {
        state cur = que.front();
        que.pop();
        if (cur.x == gx && cur.y == gy)return dis[cur.x][cur.y];
        for (int i = 0; i < 4; i++) {
            int nx = cur.x + dx[i], ny = cur.y + dy[i];
            if (dis[nx][ny] == INF && map[nx][ny] != 'X') {
                dis[nx][ny] = dis[cur.x][cur.y] + 1;
                state news;
                news.x = nx, news.y = ny;
                que.push(news);
            }
        }
    }
}

void solve() {
    int ans = 0;
    for (int i = 0; i <= k - 1;i++) {
        ans += bfs(p[i].x, p[i].y, p[i + 1].x, p[i + 1].y);
    }
    printf("%d\n", ans);
}

int main() {
    scanf("%d%d%d", &n, &m, &k);
    for (int i = 0; i < n; i++)
        scanf("%s", map[i]);
    for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++) {
            if (map[i][j] == 'S')
                p[0].x = i, p[0].y = j;
            if (map[i][j] != 'X' && map[i][j] != 'S') {
                int id = map[i][j] - '0';
                p[id].x = i;
                p[id].y = j;
            }
        }
    solve();
    return 0;
}

C++: #include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
using namespace std;
typedef pair<int,int>P;
const int maxn = 1005;
char Map[maxn][maxn];
int dx[]={0,0,1,-1},dy[]={1,-1,0,0};
int dis[maxn][maxn];
P fac[10];
int n,h,w;
int bfs(P a,P b){
    for(int i=0;i<h;i++)for(int j=0;j<w;j++)dis[i][j]=-1;
    queue<P>que;
    que.push(a);
    dis[a.first][a.second]=0;
    while(que.size()){
        P p = que.front();que.pop();
        if(p==b)break;
        for(int i=0;i<4;i++){
            int nx=dx[i]+p.first;
            int ny=dy[i]+p.second;
            if(0<=nx&&nx<h&&0<=ny&&ny<w&&Map[nx][ny]!='X'&&dis[nx][ny]==-1){
                que.push(P(nx,ny));
                dis[nx][ny]=dis[p.first][p.second]+1;
            }
        }
    }
    return dis[b.first][b.second];
}
int main()
{
    cin>>h>>w>>n;
    for(int i=0;i<h;i++){
        for(int j=0;j<w;j++){
            cin>>Map[i][j];
            if(Map[i][j]=='S'){
                fac[0].first=i;
                fac[0].second=j;
                Map[i][j]='.';
            }
            else if('1'<=Map[i][j]&&Map[i][j]<='9'){
                int flag = Map[i][j] - '0';
                fac[flag].first=i;
                fac[flag].second=j;
            }
        }
    }
    int setp = 0;
    for(int i=0;i<n;i++){
        setp += bfs(fac[i],fac[i+1]);
    }
    cout<<setp<<endl;
    return 0;
}