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 <unordered_map>
#include <utility>
#include <array>
#include <cstring>

bool isObstacle[1000][1000];
bool done[1000][1000];

int main() {
	int h, w, n;
	std::cin >> h >> w >> n;

	std::unordered_map<int, int> factories;

	for (int i = 0; i < h; ++i) {
		for (int j = 0; j < w; ++j) {
			char c;
			std::cin >> c;

			if (c == 'S')
				factories[0] = j * 1000 + i;
			else if ('1' <= c && c <= '9')
				factories[c - '0'] = j * 1000 + i;
			else if (c == 'X')
				isObstacle[j][i] = true;
		}
	}

	int ans = 0;
	for (int i = 0; i < n; ++i) {
		const int sx = factories[i] / 1000, sy = factories[i] % 1000;
		const int gx = factories[i + 1] / 1000, gy = factories[i + 1] % 1000;

		std::memset(done, 0, sizeof(done));

		done[sx][sy] = true;

		auto candidate = [h, w](int x, int y) {
			std::array<int, 4> arr;
			arr[0] = ((x == 0 || isObstacle[x - 1][y] || done[x - 1][y]) ? -1 : (done[x - 1][y] = true, (x - 1) * 1000 + y));
			arr[1] = ((x == w - 1 || isObstacle[x + 1][y] || done[x + 1][y]) ? -1 : (done[x + 1][y] = true, (x + 1) * 1000 + y));
			arr[2] = ((y == 0 || isObstacle[x][y - 1] || done[x][y - 1]) ? -1 : (done[x][y - 1] = true, x * 1000 + y - 1));
			arr[3] = ((y == h - 1 || isObstacle[x][y + 1] || done[x][y + 1]) ? -1 : (done[x][y + 1] = true, x * 1000 + y + 1));

			return std::move(arr);
		};

		std::queue<std::pair<int, int>> q;
		q.push({ factories[i], 0 });
		while (!q.empty()) {
			const auto& top = q.front();
			const int nx = top.first / 1000, ny = top.first % 1000;
			int cost = top.second;

			auto&& c = candidate(nx, ny);
			for (auto v : c) {
				if (v != -1) {
					if (v / 1000 == gx && v % 1000 == gy) {
						ans += cost + 1;
						q.pop();
						goto end;
					}
					q.push({ v, cost + 1 });
				}
			}

			q.pop();
		}
	end:;
	}

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

C++: #include "bits/stdc++.h"
using namespace std;

#define rep(i,a,b) for(int i=(a), i##_len=(b);i<i##_len;i++)
#define rrep(i,a,b) for(int i=(b)-1;i>=(a);i--)
#define all(c) begin(c),end(c)

//#define int long long
#define SZ(x) ((int)(x).size())
#define pb push_back
#define mp make_pair

typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef pair<ll, int> pli;
typedef pair<double, double> pdd;

template<class T> bool chmax(T &a, const T &b) { if (a < b) { a = b; return true; } return false; }
template<class T> bool chmin(T &a, const T &b) { if (b < a) { a = b; return true; } return false; }

const int INF = sizeof(int) == sizeof(long long) ? 0x3f3f3f3f3f3f3f3fLL : 0x3f3f3f3f;
const int MOD = (int)1e9 + 7;
const double EPS = 1e-9;

struct P
{
	int x, y, t;
	P(int x, int y, int t) :x(x), y(y), t(t){}
	P() :P(-1, -1,-1) {}
};

string A[1000];
int cnt[1000][1000];
int H, W, N;

int solve(P sp)
{
	static const int dx[] = { 1,0,-1,0 };
	static const int dy[] = { 0,1,0,-1 };

	int ans = 0;
	rep(k, 1, N + 1)
	{
		queue<P> q;
		q.push(sp);
		cnt[sp.y][sp.x] = k;
		while (true)
		{
			P tp = q.front(); q.pop();
			if ((int)A[tp.y][tp.x] == ((int)'0' + k))
			{
				sp = P(tp.x, tp.y, 0);
				ans += tp.t;
				break;
			}

			rep(i, 0, 4)
			{
				P np(tp.x + dx[i], tp.y + dy[i], tp.t + 1);
				if (0 <= np.x&&np.x < W && 0 <= np.y&&np.y < H)
				{
					if (A[np.y][np.x] != 'X'&&cnt[np.y][np.x] < k)
					{
						cnt[np.y][np.x] = k;
						q.push(np);
					}
				}
			}
		}
	}

	return ans;
}

signed main()
{
	cin.tie(0);
	ios::sync_with_stdio(false);

	P sp;
	cin >> H >> W >> N;
	rep(i, 0, H)
	{
		cin >> A[i];
		if (sp.x == -1)
		{
			rep(j, 0, SZ(A[i]))
			{
				if (A[i][j] == 'S')
				{
					sp = P(j, i, 0);
					break;
				}
			}
		}
	}
	cout << solve(sp) << endl;

	return 0;
}

C++: #include <bits/stdc++.h>
using namespace std;
#define int long long   // <-----!!!!!!!!!!!!!!!!!!!

#define rep(i,n) for (int i=0;i<(n);i++)
#define rep2(i,a,b) for (int i=(a);i<(b);i++)
#define rrep(i,n) for (int i=(n)-1;i>=0;i--)
#define rrep2(i,a,b) for (int i=(b)-1;i>=(a);i--)
#define all(a) (a).begin(),(a).end()

typedef long long ll;
typedef pair<int, int> P;
typedef tuple<int, int, int> TUPLE;
typedef vector<int> V;
typedef vector<V> VV;
typedef vector<VV> VVV;

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

const int MAX_H = 1000;
int H, W;
string s[MAX_H];

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

int bfs(int sx, int sy, int gx, int gy) {
    queue<P> que;
    que.push(P(sx, sy));
    vector<vector<int>> d(H, vector<int>(W, INF));
    d[sx][sy] = 0;

    while (!que.empty()) {
        P p = que.front(); que.pop();
        if (p.first == gx && p.second == gy)
             break;

        rep(k, 4) {
            int nx = p.first + dx[k], ny = p.second + dy[k];

            if (inside(nx, ny) && s[nx][ny] != 'X' && d[nx][ny] == INF) {
                que.push(P(nx, ny));
                d[nx][ny] = d[p.first][p.second] + 1;
            }
        }
    }
    return d[gx][gy];
}

signed main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(0);

    int N;
    cin >> H >> W >> N;
    N++;
    vector<int> x(N);
    vector<int> y(N);
    rep(i, H) {
        cin >> s[i];
        rep(j, W) {
            if (s[i][j] == 'S') s[i][j] = '0';

            if (isdigit(s[i][j])) {
                x[s[i][j] - '0'] = i;
                y[s[i][j] - '0'] = j;
            }
        }
    }

    int ans = 0;
    rep(i, N - 1) {
        ans += bfs(x[i], y[i], x[i + 1], y[i + 1]);
    }
    cout << ans << endl;

}