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 <fstream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#include <stack>
#include <array>
#include <deque>
#include <algorithm>
#include <utility>
#include <cstdint>
#include <functional>
#include <iomanip>
#include <numeric>
#include <assert.h>
#include <bitset>
 
#define MOD 1000000007
#define INF 11234567890
#define in std::cin
#define out std::cout
#define rep(i,N) for(LL i=0;i<N;++i)
typedef long long int LL;
typedef std::pair<LL, LL> P;
struct edge { LL to, cost; };
 
LL H, W, N;
std::string field[1123];
LL Sx, Sy, xy[11];
LL ans;
 
LL d[1123456];
std::vector<edge>G[1123456];
void dijkstra(LL s)
{
    std::priority_queue<P, std::vector<P>, std::greater<P>>que;
    std::fill(d, d + H * W + 1, INF);
    d[s] = 0;
    que.push(P(0, s));
    while (!que.empty())
    {
        P p = que.top(); que.pop();
        LL v = p.second;
        if (d[v] < p.first) { continue; }
        rep(i, G[v].size())
        {
            edge e = G[v][i];
            if (d[e.to] > d[v] + e.cost)
            {
                d[e.to] = d[v] + e.cost;
                que.push(P(d[e.to], e.to));
            }
        }
    }
}
 
int main()
{
return 0;
    try {
        in >> H >> W >> N;
        rep(i, H) { in >> field[i]; }
 
        rep(h, H)
        {
            rep(w, W)
            {
                if (field[h][w] == 'X') { continue; }
                if (field[h][w] == 'S') { Sx = h; Sy = w; }
                if (field[h][w] != '.') { xy[field[h][w] - '0'] = h*W + w; }
                if (h < H - 1)
                {
                    if (field[h + 1][w] != 'X')
                    {
                        G[h*W + w].push_back({ (h + 1)*W + w,1 });
                        G[(h + 1)*W + w].push_back({ h*W + w,1 });
                    }
                }
                if (w < W - 1)
                {
                    if (field[h][w + 1] != 'X')
                    {
                        G[h*W + w].push_back({ h*W + (w + 1),1 });
                        G[h*W + (w + 1)].push_back({ h*W + w,1 });
                    }
                }
            }
        }
        //dijkstra(Sx*W + Sy);
        //rep(i, N)
        //{
        //  ans += d[xy[i + 1]];
        //  dijkstra(xy[i + 1]);
        //}
 
        out << ans << std::endl;
        return 0;
    }
    catch (std::bad_alloc) { return 0; }
    catch (...) { return 0; }
}

C++: #include<iostream>
#include<queue>
#define fi first
#define se second
using namespace std;
int dy[4]={0,0,-1,1},dx[4]={1,-1,0,0};
int X,Y,N;
typedef pair<int,int> P;
char field[1000][1001];
P time[1000][1001];
struct point{
    int y,x,t,n;
};
int bfs(int,int);
int main(){
    cin>>Y>>X>>N;
    int rep;
    for(int i=0;i<Y;i++)cin>>field[i];
    for(int i=0;i<Y;i++){
        for(int j=0;j<X;j++){
            time[i][j].fi=time[i][j].se=-1;
        }
    }
    for(int i=0;i<Y;i++){
        bool flag=false;
        for(int j=0;j<X;j++){
            if(field[i][j]=='S'){
                rep=bfs(i,j);
                flag=true;
                break;
            }
        }
        if(flag)break;
    }
    cout<<rep<<endl;
    return 0;

}

int bfs(int y,int x){
    point start={y,x,0,0};
    queue<point>Q;
    Q.push(start);
    while(Q.size()){

        point a;
        a=Q.front();
        Q.pop();
        if(a.y<0 || a.y>=Y ||a.x<0||a.x>=X)continue;

        if(field[a.y][a.x]=='X')continue;

        if(a.n+1==field[a.y][a.x]-'0')a.n++;

        if(a.n>time[a.y][a.x].se){
            time[a.y][a.x].fi=a.t;
            time[a.y][a.x].se=a.n;
        }else if(a.n==time[a.y][a.x].se&&a.t<time[a.y][a.x].fi){
            time[a.y][a.x].fi=a.t;
        }else continue;

        if(a.n==N){
            return a.t;
        }


        for(int i=0;i<4;i++){
            point next={a.y+dy[i],a.x+dx[i],a.t+1,a.n};
            Q.push(next);
        }


    }



}

C++: #include <iostream>
#include <vector>
#include <string>
#include <cstring>
#include <algorithm>
#include <sstream>
#include <map>
#include <set>
#include <queue>

#define REP(i,k,n) for(int i=k;i<n;i++)
#define rep(i,n) for(int i=0;i<n;i++)
#define INF 1<<30
#define pb push_back
#define mp make_pair

using namespace std;
typedef long long ll;
typedef pair<int,int> P;

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

bool can(int y,int x) {
	if(0 <= y && y < h && 0 <= x && x < w) return true;
	return false;
}

int main() {
	cin >> h >> w >> n;

	vector<string> s(h);
	rep(i, h) cin >> s[i];

	int sx = -1, sy = -1;
	rep(i, h) {
		rep(j, w) {
			if(s[i][j] == 'S') {
				sy = i;
				sx = j;
			}
		}
	}

	int ans = 0, y = sy, x = sx;
	int d[1005][1005];
	bool used[1005][1005];

	rep(i, n) {
		queue<P> que;
		que.push(P(y, x));

		memset(used, 0, sizeof(used));
		used[y][x] = x;

		memset(d, 0, sizeof(d));
		int cnt = 0;

		while(que.size()) {
			P p = que.front();
			que.pop();

			if(s[p.first][p.second] == char('1' + i)) {
				ans += d[p.first][p.second];
				y = p.first;
				x = p.second;
				break;
			}

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

				if(can(ny, nx) && !used[ny][nx] && s[ny][nx] != 'X') {
					used[ny][nx] = true;
					d[ny][nx] += d[p.first][p.second] + 1;
					que.push(P(ny, nx));
				}
			}
		}
	}

	cout << ans << endl;
	return 0;
}