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 <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;
int r,c,n;
int ans;
char map[1005][1005];
bool book[1005][1005];
int dir[4][2]={{-1,0},{0,-1},{0,1},{1,0}};
struct point
{
    int x,y;
    int step;
}p[11],now,last;
bool check(int x,int y)
{
    if(x<0||x>=r||y<0||y>=c)
        return 0;
    return 1;
}
void bfs(int st)
{
    p[st].step=0;
    queue<point> q;
    now=p[st];
    q.push(now);
    book[now.x][now.y]=1;
    while(!q.empty())
    {
        now=q.front();
        q.pop();
        for(int i=0;i<4;i++)
        {
            last.x=now.x+dir[i][0];
            last.y=now.y+dir[i][1];
            last.step=now.step+1;
            if(!check(last.x,last.y))    continue;
            if(map[last.x][last.y]=='X'|| book[last.x][last.y]==1)    continue;
            if(last.x==p[st+1].x && last.y==p[st+1].y)
            {
                ans+=last.step;
                return;
            }
            book[last.x][last.y]=1;
            q.push(last);
        }
    }
}
int main()
{
    while(~scanf("%d%d%d",&r,&c,&n))
    {
        for(int i=0;i<r;i++)
        {
            getchar();
            for(int j=0;j<c;j++)
            {
                scanf("%c",&map[i][j]);
                if(map[i][j]=='S')
                {
                    p[0].x=i;
                    p[0].y=j;
                }
                if(map[i][j]!='S'&&map[i][j]!='X'&&map[i][j]!='.')
                {
                    p[map[i][j]-'0'].x=i;
                    p[map[i][j]-'0'].y=j;
                }
            }
        }
        ans=0;
        for(int i=0;i<n;i++)
        {
            memset(book,0,sizeof(book));
            bfs(i);
        }
        cout<<ans<<endl;
    }
    //system("pause");
    return 0;
}

C++: // c++ cpp.cpp -o cpp.exe -std=c++14

#include <iostream>
#include <vector>
#include <string>
#include <queue>
using namespace std;

#define rep(i, n) for (int i = 0; i < (n); i++)

struct hw
{
    int h, w;
};

hw start;
int h, w, n;
vector<string> maze;

int cnt = 0;
vector<vector<int>> visited;

int bfs(int target)
{
    visited.resize(h);
    rep(j, h)
    {
        visited[j].resize(w);
        rep(i, w)
        {
            visited[j][i] = -1;
        }
    }
    queue<hw> q;
    q.push(start);
    visited[start.h][start.w] = 0;

    while (!q.empty())
    {
        hw now = q.front();
        q.pop();
        if (maze[now.h][now.w] == target + '0')
        {
            start = now;
            return visited[now.h][now.w];
        }
        hw nxt;
        for (int i = -1; i <= 1; i++)
        {
            for (int j = -1; j <= 1; j++)
            {
                if ((i == 0 && j == 0) || (i != 0 && j != 0))
                {
                    continue;
                }
                nxt = {now.h + i, now.w + j};
                if (nxt.h < 0 || nxt.h == h || nxt.w < 0 || nxt.w == w)
                {
                    continue;
                }
                else if (maze[nxt.h][nxt.w] == 'X')
                {
                    continue;
                }
                else if (visited[nxt.h][nxt.w] == -1)
                {
                    q.push(nxt);
                    visited[nxt.h][nxt.w] = visited[now.h][now.w] + 1;
                }
            }
        }
    }
}

int main()
{
    cin >> h >> w >> n;
    maze.resize(h);
    rep(i, h)
    {
        cin >> maze[i];
    }

    rep(j, h)
    {
        rep(i, w)
        {
            if (maze[j][i] == 'S')
            {
                start = {j, i};
            }
        }
    }
    rep(i, n)
    {
        cnt += bfs(i + 1);
    }
    cout << cnt << endl;
}

C++: #include <iostream>
#include <cstdio>
#include <string.h>
#include <queue>
#include <algorithm>
#include <math.h>
using namespace std;
typedef pair<int, int> P;
struct info{int x, y, p, t; };
const int MAX_W = 1005;
const int MAX_N = 10;
const int INF = MAX_W * MAX_W * MAX_N;
int W;
int H;
int N;  //チーズの数
int tile[MAX_W][MAX_W];  //障害物
int arrived[MAX_N];  //チーズ
int checked[MAX_N+1][MAX_W][MAX_W];
//上、右、下、左
const int dx[] = {0,1,0,-1};
const int dy[] = {-1,0,1,0};

bool C(int x, int y) {
    return (x >= 0 && x < W && y >= 0 && y < H);
}

int main(int argc, const char * argv[])
{
    scanf("%d %d %d", &H, &W, &N);
    fill(arrived, arrived+N+1, INF);
    for (int i = 1; i <= N; i++) {
        for (int j = 0; j < W; j++) {
            fill(checked[i][j], checked[i][j] + H, INF);
        }
    }
    int sx, sy;
    for (int i = 0; i < H; i++) {
        for (int j = 0; j < W; j++) {
            char c;
            scanf(" %c", &c);
            if (c == '.') {  //空き地
                tile[j][i] = 0;
            } else if (c == 'X') {  //障害物
                tile[j][i] = INF;
            } else if (c == 'S') {
                sx = j;
                sy = i;
                tile[j][i] = 0;
            } else {
                int num = c - '0';
                tile[j][i] = num;
            }
        }
    }
    queue<info> que;
    que.push((info){sx, sy, 1, 0});
    while (!que.empty()) {
        info in = que.front(); que.pop();
        int px = in.x;
        int py = in.y;
        int pp = in.p;
        int pt = in.t;
        if (pt > arrived[pp]) continue;  //最短ではない
        if (pt >= checked[pp][px][py]) continue;  //既に訪れている
        checked[pp][px][py] = pt;  //最短経路
        if (tile[px][py] == pp) {  //工場ppに到着
            arrived[pp] = pt;
            pp++;  //体力がアップ
            checked[pp][px][py] = pt;
            if (pp == N+1) break;  //最後の工場に到着
        }
        for (int i = 0; i < 4; i++) {
            int nx = px + dx[i];
            int ny = py + dy[i];
            if (C(nx, ny) && tile[nx][ny] != INF) {  //範囲内かつ障害物ではない
                que.push((info){nx, ny, pp, pt+1});
            }
        }
    }
    printf("%d\n", arrived[N]);
    return 0;
}