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) << std::endl;
	return 0;
}

C++: #include <stdio.h>

#include <utility>
#include <queue>

using namespace std;

#define INF 1001001

typedef pair<int, int> P;

int main(void){
    queue<P> q;
    P p;
    int i,j,k,h,w,n,dx[4]={1,-1,0,0},dy[4]={0,0,1,-1},ans=0,d[1000][1000];
    char map[1000][1002];
    scanf("%d%d%d",&h,&w,&n);
    for(i=0; i<h; i++){
        scanf("%s",map[i]);
    }
    for(i=0; i<n; i++){
        for(j=0; j<h; j++){
            for(k=0; k<w; k++){
                d[j][k] = INF;
                if(map[j][k]=='S'){
                    q.push(P(j,k));
                    map[j][k]='.';
                    d[j][k] = 0;
                }
            }
        }
        while(!q.empty()){
            p = q.front();
            q.pop();
            if(map[p.first][p.second]=='1'+i){
                ans+=d[p.first][p.second];
                map[p.first][p.second]='S';
                break;
            }
            for(j=0; j<4; j++){
                int nx = p.first + dx[j];
                int ny = p.second + dy[j];
                if(nx>-1 && nx<h && ny>-1 && ny<w && map[nx][ny]!='X' && d[nx][ny]==INF){
                    q.push(P(nx,ny));
                    d[nx][ny]=d[p.first][p.second]+1;
                }
            }
        }
        while(!q.empty()){
            q.pop();
        }
    }
    printf("%d\n",ans);
    return 0;
}

C++: #include<cstdio>
#include<cstdlib>
#include<queue>
#include<algorithm>
#define INF 1000000
using namespace std;
typedef pair<int,int> P;
int dx[4]={-1,0,1,0};
int dy[4]={0,1,0,-1};
bool map[1000][1000];
int x[10],y[10];
int ans=0;
int h,w;
int search(int n){
    int d[1000][1000];
    fill(d[0],d[0]+1000*1000,INF);
    int sx=x[n],sy=y[n];
    int tx=x[n+1],ty=y[n+1];
    queue<P> q;
    q.push(P(sx,sy));
    d[sx][sy]=0;
    while(!q.empty()){
        P p=q.front();
        q.pop();
        sx=p.first,sy=p.second;
        if(sx==tx&&sy==ty) return d[tx][ty];
        for(int i=0;i<4;i++){
            int X=sx+dx[i];
            int Y=sy+dy[i];
            if(map[X][Y]&&X>=0&&X<h&&Y>=0&&Y<w&&d[X][Y]==INF){
                q.push(P(X,Y));
                d[X][Y]=d[sx][sy]+1;
            }
        }
    }
    return d[tx][ty];
}
int main(){
    int n;
    scanf("%d %d %d",&h,&w,&n);
    fill(map[0],map[0]+1000*1000,false);
    getchar();
    for(int i=0;i<h;i++){
        for(int j=0;j<w;j++){
            char c=getchar();
            if(c!='X'){
                map[i][j]=true;
                if(c=='S'){
                    x[0]=i,y[0]=j;
                }else{
                    int k=(int)c-48;
                    x[k]=i;
                    y[k]=j;
                }
            }
        }
        getchar();
    }
    for(int i=0;i<n;i++){
        int tmp=search(i);
        ans+=tmp;
    }
    printf("%d\n",ans);
}