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>
std::vector<std::pair<int, int>> next_list(const int &x, const int &y) {
	return { std::make_pair(x + 1, y), std::make_pair(x - 1, y), std::make_pair(x, y + 1), std::make_pair(x, y - 1) };
}
template<typename T>
class Queue {
public:
	Queue(const int &n) :vector(n), f(0), b(0) {};
	T front() const {
		return vector.at(f);
	}
	T back() const {
		return vector.at(b);
	}
	void pop() {
		f = (f + 1) % vector.size();
	}
	void push(T f) {
		vector.at(b) = f;
		b = (b + 1) % vector.size();
	}
	void clear() {
		f = 0;
		b = 0;
	}
private:
	std::vector<T> vector;
	int f, b;
};
struct Route {
	Route(const int &ax = 0, const int &ay = 0, const int &an = 0, const int &atime = 0) :x(ax), y(ay), n(an), time(atime) {};
	int x, y, n, time;
	bool operator<(const Route &other) const {
		return time < other.time;
	}
};
int wfs(const std::vector<std::vector<int>> &vector, std::vector<std::vector<int>> &memo, Queue<Route> &queue, const Route &start, const int &goal) {
	queue.clear();
	queue.push(start);
	while (vector.at(queue.front().y).at(queue.front().x) != start.n + 1) {
		for (const auto &coord : next_list(queue.front().x, queue.front().y)) {
			if (vector.at(coord.second).at(coord.first) >= 0 && memo.at(coord.second).at(coord.first) != start.n) {
				memo.at(coord.second).at(coord.first) = start.n;
				queue.push(Route(coord.first, coord.second, 0, queue.front().time + 1));
			}
		}
		queue.pop();
	}
	if (start.n + 1 == goal) {
		return queue.front().time;
	}
	else {
		return wfs(vector, memo, queue, Route(queue.front().x, queue.front().y, start.n + 1, queue.front().time), goal);
	}
}
int main() {
	int h, w, n;
	std::cin >> h >> w >> n;
	std::vector<std::vector<int>> vector(h + 2, std::vector<int>(w + 2, -1));
	Route start(0, 0, 0, 0);
	char *arg = new char[w + 2];
	for (auto i = 1; i <= h; ++i) {
		std::cin >> arg;
		for (auto j = 1; j <= w; ++j) {
			switch (arg[j - 1]) {
			case '.':
				vector.at(i).at(j) = 0;
				break;
			case 'X':
				vector.at(i).at(j) = -1;
				break;
			case 'S':
				vector.at(i).at(j) = 0;
				start = Route(j, i, 0, 0);
				break;
			default:
				vector.at(i).at(j) = arg[j - 1] - '0';
			}
		}
	}
	delete[] arg;
	arg = nullptr;
	std::vector<std::vector<int>> memo(h + 2, std::vector<int>(w + 2, -1));
	Queue<Route> queue(h * w * 4);
	std::cout << wfs(vector, memo, queue, start, n);
	return 0;
}

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

typedef long long ll;
typedef unsigned long long ull;
typedef unsigned __int128 HASH;
typedef pair<int,int> pii;
typedef pair<ll, ll> pll;
typedef pair<ull, ull> pullull;
typedef pair<ll,int> plli;
typedef pair<double, int> pdbi;
typedef pair<int,pii> pipii;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector<vi> vvi;
typedef vector<vvi> vvvi;
typedef vector<pii> vpii;
typedef vector<vector<int>> mat;

#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);i>0;i--)
#define rrep2(i,a,b) for (int i=(a);i>b;i--)
#define pb push_back
#define fi first
#define se second
#define all(a) (a).begin(),(a).end()
#define rall(a) (a).rbegin(),(a).rend()

const ll hmod1 = 999999937;
const ll hmod2 = 1000000000 + 9;
const ll INF = 1<<30;
const ll mod = 10000;
const int dx4[4] = {1, 0, -1, 0};
const int dy4[4] = {0, 1, 0, -1};
const int dx8[8] = {1, 1, 1, 0, 0, -1, -1, -1};
const int dy8[8] = {0, 1, -1, 1, -1, 0, 1, -1};
const double pi = 3.141592653589793;

//#define int long long
#define addm(X, Y) ((X) = ((X) + (Y) % mod) % mod)

int h, w, n;
char g[1000 + 5][1000 + 5];
int sx, sy;

bool check(int y, int x) {
    if (0 <= y && y < h && 0 <= x && x < w) {
        if (g[y][x] != 'X') return true;
    }
    return false;
}

signed main(){
    cin.tie(0);
    ios::sync_with_stdio(false);
    cin >> h >> w >> n;
    rep(i, h)rep(j, w) {
        cin >> g[i][j];
        if (g[i][j] == 'S') {
            sy = i;
            sx = j;
        }
    }
    int ans = 0;
    int dist[h][w] = {};
    bool visited[h][w] = {};
    int nowy = sy, nowx = sx;
    rep(i, n) {
        rep(i, h)rep(j, w) {
            dist[i][j] = INF;
            visited[i][j] = false;
        }
        queue<pair<int, int>> q;
        q.push({nowy, nowx});
        dist[nowy][nowx] = 0;
        visited[nowy][nowx] = true;
        while (q.size() != 0) {
            pair<int, int> now = q.front(); q.pop();
            rep(j, 4) {
                int ny = now.fi + dy4[j];
                int nx = now.se + dx4[j];
                if (!check(ny, nx) || visited[ny][nx]) continue;
                q.push({ny, nx});
                visited[ny][nx] = true;
                dist[ny][nx] = dist[now.fi][now.se] + 1;
                if (g[ny][nx] - '0' == i + 1) {
                    ans += dist[ny][nx];
                    nowy = ny;
                    nowx = nx;
                    break;
                }
            }
        }
    }
    cout << ans << endl;
}

C++: #include<stdio.h>
#include<map>
#include<queue>
#define INF 10000000
using namespace std;
typedef pair<int,int> P;
int h,w;
bool pos[1000][1000];
int d[1000][1000];
P p[10];
queue<P> que;
int dx[4]={-1,0,1,0};
int dy[4]={0,1,0,-1};
int bfs(P s,P g){
	int i,j;
	for(i=0;i<h;i++)for(j=0;j<w;j++)d[i][j]=INF;
	d[s.first][s.second]=0;
	que.push(s);
	while(!que.empty()){
		P x=que.front();que.pop();
		for(i=0;i<4;i++){
			int nx=x.first+dx[i];
			int ny=x.second+dy[i];
			if(nx>=0&&nx<h&&ny>=0&&ny<w&&pos[nx][ny]&&d[nx][ny]==INF){
				d[nx][ny]=d[x.first][x.second]+1;
				que.push(P(nx,ny));
			}
		}
	}
	return d[g.first][g.second];
}
int main(){
	int n;
	int i,j;
	scanf("%d %d %d",&h,&w,&n);
	for(i=0;i<h;i++)for(j=0;j<w;j++)pos[i][j]=true;
	for(i=0;i<h;i++){
		for(j=0;j<w;j++){
			char c;
			scanf(" %c",&c);
			if(c=='X')pos[i][j]=false;
			if(c=='S')p[0]=P(i,j);
			if(c>='1'&&c<='9')p[c-'0']=P(i,j);
		}
	}
	int ans=0;
	for(i=0;i<n;i++){
		ans+=bfs(p[i],p[i+1]);
	}
	printf("%d\n",ans);
	return 0;
}