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

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

constexpr int MAX_HW = 1000;
constexpr int MAX_N = 9;
constexpr int dx[] = {1, 0, -1, 0}, dy[] = {0, 1, 0, -1};

int H, W, N;
int sx[MAX_N], sy[MAX_N], gx[MAX_N], gy[MAX_N];
char map[MAX_HW][MAX_HW];

int bfs(const int& n);

int main(){
    scanf("%d%d%d", &H, &W, &N);
    
    for(int i = 0; i < H; ++i){
        scanf("\n");
        for(int j = 0; j < W; ++j){
            scanf("%c", &map[j][i]);
            if(map[j][i] == 'S'){
                sx[0] = j, sy[0] = i;
            }
            if(map[j][i] >= '1' && map[j][i] < (N + '0')){
                sx[map[j][i] - '0'] = j, sy[map[j][i] - '0'] = i;
                gx[map[j][i] - '0' - 1] = j, gy[map[j][i] - '0' - 1] = i;
            }
            if(map[j][i] == (N + '0')){
                gx[N - 1] = j, gy[N - 1] = i;
            }
        }
    }
    
    int ans = 0;
    for(int i = 0; i < N; ++i){
        ans += bfs(i);
    }
    
    printf("%d\n", ans);
    
    return 0;
}

int bfs(const int& n){
    int dis[MAX_HW][MAX_HW];
    memset(dis, -1, sizeof(dis));
    dis[sx[n]][sy[n]] = 0;
    
    std::queue<Pair> que;
    que.push(Pair(sx[n], sy[n]));
    
    while(que.size()){
        Pair p = que.front(); que.pop();
        
        if(p.first == gx[n] && p.second == gy[n]){
            break;
        }
        
        for(int i = 0; i < 4; ++i){
            int nx = p.first + dx[i], ny = p.second + dy[i];
            if(nx >= 0 && ny >= 0 && nx < W && ny < H && map[nx][ny] != 'X' && dis[nx][ny] == -1){
                que.push(Pair(nx, ny));
                dis[nx][ny] = dis[p.first][p.second] + 1;
            }
        }
    }
    
    return dis[gx[n]][gy[n]];
}

C++: #include <iostream>
#include <string>
#include <queue>
int a[1005][1005];
bool tf[1005][1005];
int p[10][2];
int dirc[4][2] = {{-1 , 0} , {1 , 0} , {0 , -1} , {0 , 1}};
int w , h , n;

int bfs(int st_y , int st_x , int en_y , int en_x){
    for(int i = 0;i < h;i++){
        for(int j = 0;j < w;j++){
            tf[i][j] = false;
        }
    }
    tf[st_y][st_x] = true;    
    int x , y , step;
    std::queue < std::tuple<int , int , int> > que;
    que.push(std::make_tuple(st_y , st_x , 0));
    while(!que.empty()){
        std::tie(y , x , step) = que.front();
        que.pop();
        if(x == en_x && y == en_y){
            return step;
        }
        for(int i = 0;i < 4;i++){
            int ny = y + dirc[i][0] , nx = x + dirc[i][1];
            if(nx >= 0 && nx < w && ny >= 0 && ny < h && a[ny][nx] >= 0 && tf[ny][nx] == false){
                tf[ny][nx] = true;
                que.push(std::make_tuple(ny , nx , step + 1));
            }
        }
    }
    return 0;
}
int main(){
    std::cin >> h >> w >> n;
    for(int i = 0;i < h;i++){
        std::string s;
        std::cin >> s;
        for(int j = 0;j < w;j++){
            switch(s[j]){
                case 'S':
                    a[i][j] = 0 , p[0][0] = i , p[0][1] = j;
                    break;
                case '.':
                    a[i][j] = 0;
                    break;
                case '1':
                    a[i][j] = 1; p[1][0] = i , p[1][1] = j;
                    break;
                case '2':
                    a[i][j] = 2; p[2][0] = i , p[2][1] = j;
                    break;
                case '3':
                    a[i][j] = 3; p[3][0] = i , p[3][1] = j;
                    break;
                case '4':
                    a[i][j] = 4; p[4][0] = i , p[4][1] = j;
                    break;
                case '5':
                    a[i][j] = 5; p[5][0] = i , p[5][1] = j;
                    break;
                case '6':
                    a[i][j] = 6; p[6][0] = i , p[6][1] = j;
                    break;
                case '7':
                    a[i][j] = 7; p[7][0] = i , p[7][1] = j;
                    break;
                case '8':
                    a[i][j] = 8; p[8][0] = i , p[8][1] = j;
                    break;
                case '9':
                    a[i][j] = 9; p[9][0] = i , p[9][1] = j;
                    break;
                default:
                    a[i][j] = -1;
                    break;
            }
        }
    }

    int ans = 0;
    for(int i = 1;i <= n;i++){
        ans += bfs(p[i - 1][0] , p[i - 1][1] , p[i][0] , p[i][1]);
    }
    std::cout << ans << "\n";
    return 0;
}

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; };

int H, W, N;
std::string field[1123];
int Sx, Sy, x[11], y[11], ans;

int d[1123][1123];
int dx[] = { 1,0,-1,0 }, dy[] = { 0,1,0,-1 };
void bfs(LL sx, LL sy, LL gx, LL gy)
{
	std::queue<P>que;
	memset(d, -1, sizeof(d));
	que.push({ sx,sy });
	d[sx][sy] = 0;
	while (que.size() > 0)
	{
		auto pos = que.front(); que.pop();
		if (pos.first == gx && pos.second == gy) { break; }
		rep(i, 4)
		{
			auto toX = pos.first + dx[i], toY = pos.second + dy[i];
			if (0 <= toX && toX < H && 0 <= toY && toY < W)
			{
				if (field[toX][toY] != 'X' && d[toX][toY] == -1)
				{
					que.push({ toX,toY });
					d[toX][toY] = d[pos.first][pos.second] + 1;
				}
			}
		}
	}
}

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

	rep(i, H)
	{
		rep(j, W)
		{
			if (field[i][j] == 'S') { Sx = i; Sy = j; }
			else if (field[i][j] != '.') { x[field[i][j] - '0'] = i; y[field[i][j] - '0'] = j; }
		}
	}
	x[0] = Sx; y[0] = Sy;
	rep(i, N)
	{
		bfs(x[i], y[i], x[i + 1], y[i + 1]);
		ans += d[x[i + 1]][y[i + 1]];
	}
	out << ans << std::endl;
	return 0;
}