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 <vector>
#include <math.h>
#include <string>
#include <stack>
using namespace std;

int h, w, n;
int map[1000][1000];
int map_t[1000][1000];
int xxx, yyy;
int ans;

void SusundeHappy(int x, int y, int goal, int n)
{
	if (map_t[x][y] == goal)
	{
		xxx = x;
		yyy = y;
	}
	map_t[x][y] = -1 * n;

	if (x > 0)
	{
		if (map_t[x - 1][y] > -1 || map_t[x - 1][y] < -1 * n)
		{
			SusundeHappy(x - 1, y, goal, n + 1);
		}
	}

	if (x < h - 1)
	{
		if (map_t[x + 1][y] > -1 || map_t[x + 1][y] < -1 * n)
		{
			SusundeHappy(x + 1, y, goal, n + 1);
		}
	}

	if (y > 0)
	{
		if (map_t[x][y - 1] > -1 || map_t[x][y - 1] < -1 * n)
		{
			SusundeHappy(x, y - 1, goal, n + 1);
		}
	}

	if (y < w - 1)
	{
		if (map_t[x][y + 1] > -1 || map_t[x][y + 1] < -1 * n)
		{
			SusundeHappy(x, y + 1, goal, n + 1);
		}
	}
	
}

int TimeFrom(int start)
{
	ans = 0;
	int goal = start + 1;
	if (start == 10)
	{
		goal = 1;
	}

	for (int i = 0; i < h; i++)
	{
		for (int j = 0; j < w; j++)
		{
			if (map_t[i][j] == start)
			{
				SusundeHappy(i, j, goal, 1);
				return -1 * map_t[xxx][yyy] - 1;
			}
		}
	}
}

int main()
{
	string line;
	while (cin >> h >> w >> n)
	{
		for (int i = 0; i < h; i++)
		{
			cin >> line;
			for (int j = 0; j < w; j++)
			{
				switch (line[j])
				{
				case 'S':
					map[i][j] = 10;
					break;

				case '.':
					map[i][j] = 0;
					break;

				case 'X':
					map[i][j] = -1;
					break;

				default:
					map[i][j] = line[j] - '0';
					break;
				}
			}
		}

		int cnt = 0;
		for (int k = 0; k < n; k++)
		{
			for (int i = 0; i < h; i++)
			{
				for (int j = 0; j < w; j++)
				{
					map_t[i][j] = map[i][j];
				}
			}
			if (k == 0)
			{
				cnt = cnt + TimeFrom(10);
			}
			else
			{
				cnt = cnt + TimeFrom(k);
			}
		}

		cout << cnt << endl;
	}


	return 0;
}

C++: #include "bits/stdc++.h"

using namespace std;

//#define int long long

#define FOR(i, a, b) for (int i = (a); i < (b); i++)
#define REP(i, n) for (int i = 0; i < (n); i++)

#define pb push_back
#define VDEL(v, n) v.erase(v.begin() + (n))
#define ALL(v) v.begin(), v.end()

#define INTMAX 2147483647
#define INF 200000000
#define TINT(str) atoi(str.c_str())
#define TSTR(num) to_string(num)

using ll = long long;
using PII = pair<int, int>;
using VI = vector<int>;
using VII = vector<vector<int>>;

int dx[4] = {0, 1, 0, -1};
int dy[4] = {1, 0, -1, 0};

PII goal[10];
char k[1000][1000];
int fx, fy;
int H,W;

int BFS(int x, int y)
{
    VII cost;
    cost = VII(H, VI(W, INF));

    cost[fx][fy] = 0;

    queue<PII> q;

    q.push(make_pair(fx, fy));

    while(!q.empty())
    {
        PII now = q.front();
        q.pop();
        int nx = now.first;
        int ny = now.second; 

        REP(i, 4)
        {
            if(nx + dx[i] >= H ||
            nx + dx[i] < 0) continue;
            if(ny + dy[i] >= W || 
            ny + dy[i] < 0) continue;

            if(nx + dx[i] == x &&
            ny + dy[i] == y)
            {
                return cost[nx][ny] + 1;
            }

            if(k[nx + dx[i]][ny + dy[i]] != 'X')
            {
                if(cost[nx + dx[i]][ny + dy[i]] > 
                cost[nx][ny])
                {
                    cost[nx + dx[i]][ny + dy[i]] =
                        cost[nx][ny] + 1;
                    q.push(make_pair(nx + dx[i], ny + dy[i]));
                }
            }
            else continue;
        }
    }

    return -1;
}

signed main()
{
    int N;
    cin >> H >> W >> N;

    char str[1001];
    REP(h, H)
    {
        scanf("%s", str);
        REP(w, W)
        {
            k[h][w] = str[w];
            if(k[h][w] == 'S')
            {
                fx = h;
                fy = w;
            }
            if(k[h][w] != '.' &&
                k[h][w] != 'X')
            {
                goal[k[h][w] - '1'] = make_pair(h, w);
            }
        }
    }
    int ans = 0;

    REP(i, N)
    {
        ans += BFS(goal[i].first, goal[i].second);
        fx = goal[i].first;
        fy = goal[i].second;
    }

    cout << ans << endl;

    return 0;
}

C++: #include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#include<cmath>
#include<stack>
#include<queue>
#include<cctype>
#define INF 100000000
using namespace std;

struct  coor
{
	int x, y;
};

char map[1002][1002];
int tim[1002][1002];
int vis[1002][1002];
int dx[4] = { 0,1,0,-1 };
int dy[4] = { 1,0,-1,0 };
int h, w, n;
coor s;
coor fac[10];
int phy;
int ans;


int bfs(coor fa)
{
	coor next;
	coor now;
	queue<coor>q;
	q.push(s);
	vis[s.x][s.y] = 1;
	while (!q.empty())
	{
		now = q.front();
		q.pop();
		if (now.x == fa.x&&now.y == fa.y)
		{
			break;
		}
		vis[now.x][now.y] = 1;
		for (int i = 0;i < 4;i++)
		{
			next.x = now.x + dx[i];
			next.y = now.y + dy[i];
			if (map[next.x][next.y] != 'X'&&next.x >= 0&& next.x < h &&next.y >= 0 && next.y < w&&!vis[next.x][next.y])
			{
				tim[next.x][next.y] = tim[now.x][now.y] + 1;
				q.push(next);
			}
		}
	}
	return tim[fa.x][fa.y];
}

void timeinit(coor st)
{
	for (int i = 0;i < h;i++)
	{
		for (int j = 0;j < w;j++)
		{
			if (map[i][j] != 'X')
				tim[i][j] = INF;
		}
	}
	tim[st.x][st.y] = 0;

}
int main()
{
	while (~scanf("%d%d%d",&h,&w,&n))
	{
		getchar();
		for (int i = 0;i < h;i++)
		{
			for (int j = 0;j < w;j++)
			{
				scanf("%c", &map[i][j]);
				tim[i][j] = INF;
				if (map[i][j] == 'S') { map[i][j] = '.';s.x = i;s.y = j; }
				if (isdigit(map[i][j]))
				{
					fac[map[i][j] - '0'].x = i;
					fac[map[i][j] - '0'].y = j;
				}
			}
			getchar();
		}

		phy = 1;
		tim[s.x][s.y] = 0;
		ans = 0;
		for (int i = 1;i <= n ;i++)
		{
			memset(vis, 0, sizeof(vis));
			ans += bfs(fac[i]);
			s.x = fac[i].x;
			s.y = fac[i].y;
			timeinit(s);
		}
		printf("%d\n", ans);
	}
	return 0;
}