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 <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <ctime>

using namespace std;

inline int toInt(string s) {int v; istringstream sin(s);sin>>v;return v;}
template<class T> inline string toString(T x) {ostringstream sout;sout<<x;return sout.str();}
template<class T> inline T sqr(T x) {return x*x;}

typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<string> vs;
typedef pair<int, int> pii;
typedef long long ll;

#define all(a)  (a).begin(),(a).end()
#define rall(a) (a).rbegin(), (a).rend()
#define pb push_back
#define mp make_pair
#define each(i,c) for(typeof((c).begin()) i=(c).begin(); i!=(c).end(); ++i)
#define exist(s,e) ((s).find(e)!=(s).end())
#define range(i,a,b) for(int i=(a);i<(b);++i)
#define rep(i,n)  range(i,0,n)
#define clr(a,b) memset((a), (b) ,sizeof(a))
#define dump(x)  cerr << #x << " = " << (x) << endl;
#define debug(x) cerr << #x << " = " << (x) << " (L" << __LINE__ << ")" << " " << __FILE__ << endl;

const double eps = 1e-10;
const double pi  = acos(-1.0);
const ll inf =1LL << 62;
const int  INF = 1 << 30;
struct node {
	int x;
	int y;
	int c;
	bool operator <(node a)const{
    return c < a.c;
  	}
	bool operator >(node a)const{
    return c > a.c;
  	}
};

int dis[1010][1010];
int nx[10];
int ny[10];
string maze[1010];
int hmax=1;

int main(void){
	int H,W,n;
	cin >> H >> W >> n;
	rep(i,H) cin >> maze[i];
	node init;
	rep(i,H) rep(j,W){
		if(maze[i][j]=='S'){
			nx[0]=j;
			ny[0]=i;
		}else if(isdigit(maze[i][j])){
			nx[maze[i][j]-'0']=j;
			ny[maze[i][j]-'0']=i;
		}
	}
	int ans=0;
	rep(j,n){
		rep(k,H)rep(l,W) dis[k][l]=INF;
		init.x=nx[j];
		init.y=ny[j];
		init.c=0;
		priority_queue <node,vector<node>,greater<node> > q;
		q.push(init);
		int dx[4]={1,0,-1,0};
		int dy[4]={0,1,0,-1};
		while(!q.empty()){
			node cur;
			cur=q.top();q.pop();
			// テァツ渉セテ・ツ慊ィテ、ツスツ催ァツスツョテ」ツ?ョテ・ツ按、テ・ツョツ堙・ツ?ヲテァツ青?
			if(dis[cur.y][cur.x]<=cur.c)
				continue;
			else
				dis[cur.y][cur.x]=cur.c;
			if(hmax==(maze[cur.y][cur.x]-'0')){
				ans+=cur.c;
				hmax++;
				break;
			}
			//テ」ツ??ヲツャツ。テ」ツ?ョテァツ環カテヲツ?凝」ツ?クテ」ツ?ョテゥツ?キテァツァツサ
			rep(i,4){
				node next;
				next.x=cur.x+dx[i];
				next.y=cur.y+dy[i];
				next.c=cur.c+1;
				if(0<=next.x&&next.x<W&&0<=next.y&&next.y<H&&maze[next.y][next.x]!='X')
					q.push(next);
			}	
		}
	}
	cout << ans << endl;
	return 0;
}

C++: #include <iostream>
#include <utility>
#include <queue>
using namespace std;

typedef pair<int, int> Pair;
const int INF = 100000000;

int H, W;
char N;
const int MAX_H = 1000, MAX_W = 1000;
char plant[MAX_H][MAX_W];
int sx, sy;
int dx[4] = {0,1,0,-1}, dy[4] = {1,0,-1,0};
int d[MAX_H][MAX_W];
int time;

void bfs() {
    queue<Pair> que;
    for (int i = 0; i < H; i++) {
        for (int j = 0; j < W; j++) {
            d[i][j] = INF;
        }
    }
    char muscle = '1';
    que.push(Pair(sx,sy));
    d[sx][sy] = 0;
    while (que.size()) {
        Pair p  = que.front(); que.pop();
        if (muscle-1 == N) break;
        for (int i = 0; i < 4; i++) {
            int nx = p.first + dx[i], ny = p.second + dy[i];
            if (0 <= nx && nx < H && 0 <= ny && ny < W && plant[nx][ny] != 'X' && d[nx][ny] == INF) {
                que.push(Pair(nx, ny));
                d[nx][ny] = d[p.first][p.second] + 1;
            }
            if (muscle == plant[nx][ny]) {
                while(que.size()) {que.pop();}
                que.push(Pair(nx, ny));
                muscle = muscle + 1;
                time += d[nx][ny];
                for (int i = 0; i < H; i++) {
                    for (int j = 0; j < W; j++) {
                        d[i][j] = INF;
                    }
                }
                d[nx][ny] = 0;
                break;
            }
        }
    }
}

void solve() {
    time = 0;
    bfs();
    cout << time << endl;
}

int main () {
    cin >> H >> W >> N;
    for (int i = 0; i < H; i++) {
        for (int j = 0; j < W; j++) {
            cin >> plant[i][j];
            if(plant[i][j] == 'S') {sx = i; sy = j;}
        }
    }
    solve();
    return 0;
}

C++: #include<set>
#include<queue>
#include<utility>
#include<cstdio>
#include<vector>
#include<algorithm>
#include<numeric>
#include<functional>
#include<string>
#include<iostream>
using namespace std;
const long long int one = 1;
const long long int big = (one<<20);
typedef long long int llint;

//	. 0x2e	X 0x58	S 0x53	1~ 0x31~
int main(void){
	int H,W,N,h,i,j,x,y,t,ans=0;
	queue<tuple<int,int,int>> que;
	static char Chezu[1002][1002];//??°?????¨???????????????????????????
	static int time[1002][1002];
	int Cx[10];
	int Cy[10];
	scanf("%d %d %d",&H,&W,&N);
	for(j=0;j<=W+1;j++){Chezu[0][j]=0x58;}
	for(i=1;i<=H;i++){Chezu[i][0]=0x58;scanf(" %s",Chezu[i]+1);Chezu[i][W+1]=0x58;}
	for(j=0;j<=W+1;j++){Chezu[H+1][j]=0x58;}

	for(i=1;i<=H;i++){
		for(j=1;j<=W;j++){
			if(Chezu[i][j]==0x53){
				Cx[0]=i;Cy[0]=j;
			}
			if(0x31<=Chezu[i][j]&&Chezu[i][j]<=0x39){
				Cx[Chezu[i][j]-0x30]=i;
				Cy[Chezu[i][j]-0x30]=j;
			}
		}
	}
	for(h=0;h<N;h++){
		while(!que.empty()){que.pop();}
		for(i=0;i<H+2;i++){
			for(j=0;j<W+2;j++){
				time[i][j]=big;
			}
		}
		que.push(make_tuple(Cx[h],Cy[h],0));
		while(!que.empty()){
			x=get<0>(que.front());
			y=get<1>(que.front());
			t=get<2>(que.front());
			que.pop();
			if(x==Cx[h+1]&&y==Cy[h+1]){break;}
			if(time[x][y]<=t){ continue; }
			time[x][y]=t;
			if(Chezu[x+1][y]!=0x58){ que.push(make_tuple(x+1,y,t+1)); }
			if(Chezu[x-1][y]!=0x58){ que.push(make_tuple(x-1,y,t+1)); }
			if(Chezu[x][y+1]!=0x58){ que.push(make_tuple(x,y+1,t+1)); }
			if(Chezu[x][y-1]!=0x58){ que.push(make_tuple(x,y-1,t+1)); }
		}
		ans+=t;
	}
	printf("%d",ans);
	return 0;
}