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++: //
//  0558.cpp
//  
//
//  Created by Yoshida Satoshi on 2017/11/16.
//
//

#include <iostream>
#include <queue>
#include <utility>
#include <stdlib.h>

#define MAX 1000
#define INF 100000000
#define FOR(index,max) for(int index=0;index<max;index++)

using namespace std;

typedef pair<int, int> P;

int ctoi(char c){
    switch(c){
        case '0': return 0;
        case '1': return 1;
        case '2': return 2;
        case '3': return 3;
        case '4': return 4;
        case '5': return 5;
        case '6': return 6;
        case '7': return 7;
        case '8': return 8;
        case '9': return 9;
        default : return -1;
    }
}

int main(){
    int dx[4]={1,-1,0,0};
    int dy[4]={0,0,1,-1};
    
    int nx,ny;
    
    queue<P> que;
    int H,W,N;
    int state[MAX][MAX];//0:????????°or????????? -1:????????¶???
    int d[MAX][MAX];
    int ans=0;
    int sx[10];
    int sy[10];
    P p;
    char in;
    cin>>H>>W>>N;
    FOR(i,H){
        FOR(j,W){
            cin>>in;
            if(in=='S'){
                sx[0]=i;
                sy[0]=j;
                state[i][j]=0;
            }
            else if(in=='X') state[i][j]=-1;
            else if(in=='.') state[i][j]=0;
            else{
                state[i][j]=0;
                sx[ctoi(in)]=i;
                sy[ctoi(in)]=j;
                
            }
        }
    }
    
    FOR(k,N){
        FOR(i,H){
            FOR(j,W){
                d[i][j]=INF;
            }
        }
        que.push(P(sx[k],sy[k]));
        d[sx[k]][sy[k]]=0;
        while(que.size()){
            p=que.front();
            que.pop();
            
            if(p==P(sx[k+1],sy[k+1]))   break;
            
            FOR(l,4){
                nx=p.first+dx[l];
                ny=p.second+dy[l];
                
                if(!(nx<0||ny<0||nx>H-1||ny>W-1||state[nx][ny]==-1||d[nx][ny]!=INF)){
                    que.push(P(nx,ny));
                    d[nx][ny]=d[p.first][p.second]+1;
                }
            }
        }
        
        ans += d[sx[k+1]][sy[k+1]];
        queue<P>().swap(que);
    }
    
    cout<<ans<<endl;
    
    return 0;
}

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

//#define int long long
#define DBG 1
#define dump(o) if(DBG){cerr<<#o<<" "<<o<<endl;}
#define dumpc(o) if(DBG){cerr<<#o; for(auto &e:(o))cerr<<" "<<e;cerr<<endl;}
#define rep(i,a,b) for(int i=(a);i<(b);i++)
#define rrep(i,a,b) for(int i=(b)-1;i>=(a);i--)
#define each(it,c) for(auto it=(c).begin();it!=(c).end();it++)
#define all(c) c.begin(),c.end()
const int INF = sizeof(int) == sizeof(long long) ? 0x3f3f3f3f3f3f3f3fLL : 0x3f3f3f3f;
const int MOD = (int)(1e9 + 7);
const double EPS = 1e-10;
void print_v(vector<vector<int>>aaa) {
	cout << endl;
	rep(i, 0, aaa.size()) {
		rep(j, 0, aaa.size()) {
			cout << aaa[i][j] << (j == aaa[i].size() - 1 ? '\n' : ' ');
		}
	}
}
int ans(0);
vector<string>v, g;
int h, w, n, cheese(1), bfs_cnt(0);
vector<vector<int>>s;
int bfs(int x, int y) {
	bfs_cnt = 0;
	queue<pair<int, int>>Q;
	Q.push(make_pair(x, y));
	s[x][y] = bfs_cnt++;
	while (!Q.empty()) {
		auto p = Q.front(); Q.pop();
		int a = p.first, b = p.second;
		if (a < 0 || h <= a || b < 0 || w <= b)continue;
		if (v[a][b] == 'X')continue;
		if (v[a][b] == '0' + cheese)return s[a][b];

		v[a][b] = 'X';
		if (a - 1 >= 0) {
			if (s[a - 1][b] == -1)s[a - 1][b] = s[a][b] + 1;
			Q.push(make_pair(a - 1, b));
		}
		if (a + 1 < h) {
			if (s[a + 1][b] == -1)s[a + 1][b] = s[a][b] + 1;
			Q.push(make_pair(a + 1, b));
		}
		if (b - 1 >= 0) {
			if (s[a][b - 1] == -1)s[a][b - 1] = s[a][b] + 1;
			Q.push(make_pair(a, b - 1));
		}
		if (b + 1 < w) {
			if (s[a][b + 1] == -1)s[a][b + 1] = s[a][b] + 1;
			Q.push(make_pair(a, b + 1));
		}
		
	}

}

int bfs_start() {
	vector<pair<int, int>>point(n + 1);
	rep(i, 0, h) {
		rep(j, 0, w) {
			if (g[i][j] == 'S')point[0] = make_pair(i, j);
			else if (isdigit(g[i][j])) {
				point[g[i][j] - '0'] = make_pair(i, j);
			}
		}
	}

	rep(i, 0, n) {
		s = vector<vector<int>>(h, vector<int>(w, -1));
		v = g;
		ans += bfs(point[i].first, point[i].second);
		cheese++;
	}
	return ans;
}

signed main() {
	cin >> h >> w >> n;
	rep(i, 0, h) {
		string s; cin >> s;
		g.push_back(s);
	}

	cout << bfs_start() << endl;


	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];
typedef struct point{
    int y,x,t,n;
}point;
int bfs(int,int);
int main(){
    cin>>Y>>X>>N;
    int rep=0;
    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);
        }


    }



}