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>
#include <queue>
#include <algorithm>

#define rep(i,a,b) for(int i=(a);i<(b);i++)
#define pb push_back
#define mp(a,b) make_pair(a,b)
#define all(a) a.begin(),a.end()
#define pii pair<int, int>
#define ll long long
using namespace std; 

#define MAX 10
#define SIZE 1000
#define INF 1<<30

int H, W, N;
char sec[SIZE][SIZE+1];
int time = INF;
int all_time = 0;
int dy[4] = {-1, 0, 1, 0};
int dx[4] = {0, 1, 0, -1};
int facy[10] = {};
int facx[10] = {};

struct state {
	int sy, sx, gy, gx, cnt;
	state() {}
	state(int _sy, int _sx, int _gy, int _gx, int _cnt) :
		sy(_sy), sx(_sx), gy(_gy), gx(_gx), cnt(_cnt) {}
};
queue<state> que;

void bfs()
{
	int **tsec = new int*[SIZE];
	rep(i,0,SIZE) tsec[i] = new int[SIZE+1];
	rep(i,0,H) rep(j,0,W) tsec[i][j] = (int)sec[i][j];
	//rep(i,0,H) { rep(j,0,W) cout << tsec[i][j] << " "; cout << endl;}

	while (!que.empty()) {
		state ts = que.front(); que.pop();
		//printf("sy=%d sx=%d gy=%d gx=%d cnt=%d\n",ts.sy,ts.sx,ts.gy,ts.gx,ts.cnt);
		if (ts.cnt > time) return;
		if (ts.sy == ts.gy && ts.sx == ts.gx) time = min(time, ts.cnt);
		tsec[ts.sy][ts.sx] = ts.cnt;

		rep(i, 0, 4) {
			int ny = ts.sy + dy[i];
			int nx = ts.sx + dx[i];
			if (ny < 0 || ny >= H) continue;
			if (nx < 0 || nx >= W) continue;
			if (sec[ny][nx] == 'X') continue;
			if (tsec[ny][nx] < ts.cnt) continue; 
			state ns(ny, nx, ts.gy, ts.gx, ts.cnt + 1);
			que.push(ns);
		}
	//rep(i,0,H) { rep(j,0,W) cout << tsec[i][j] << " "; cout << endl;}
	}

	rep(i,0,SIZE) delete[] tsec[i];
	delete[] tsec;
}

void solve()
{
	// rep(i,0,N+1) printf("%d y=%d x=%d\n",i,facy[i],facx[i]);

	rep(i,0,N) {
		time = INF;
		while(!que.empty()) que.pop();
		state s(facy[i], facx[i], facy[i+1], facx[i+1], 0);
		que.push(s);
		//printf("\n bfs start !! \n");
		bfs();
		all_time += time;
	}

	cout << all_time << endl;
}

void input()
{
	cin >> H >> W >> N;
	rep(i,0,H) { 
		rep(j,0,W) {
			cin >> sec[i][j];
			if (sec[i][j] == 'S') { facy[0] = i; facx[0] = j; }
			if (sec[i][j] >= 49 && 57 >= sec[i][j]) {
				facy[sec[i][j]-48] = i;
				facx[sec[i][j]-48] = j;
			}
		}
	}
	solve();
}

int main(void)
{
	input();
	
	return 0;
}

C++: #include <cstdio>
#include <cstring>
#include <iostream>
#include <string>
#include <algorithm>
#include <queue>
#include <stack>
using namespace std;
int h, w, n, result;
char map[1005][1005];
bool vis[1005][1005];
int x[10], y[10];
int dx[] = {0, 1, 0, -1};
int dy[] = {1, 0, -1, 0};
struct Node
{
    int x, y;
    int step;
};
void BFS(int sx, int sy, int target)
{
    queue <Node> que;

    Node s, t;
    s.x = sx;
    s.y = sy;
    s.step = 0;
    memset(vis, false, sizeof(vis));

    que.push(s);
    vis[sx][sy] = true;

    while(!que.empty())
    {
        s = que.front();
        que.pop();

        if(map[s.x][s.y] == target + '0')
        {
            result += s.step;
            break;
        }

        for(int i = 0; i < 4; i++)
        {
            int tx = s.x + dx[i];
            int ty = s.y + dy[i];

            if(tx >= 0 && tx < h && ty >= 0 && ty < w && !vis[tx][ty] && map[tx][ty] != 'X')
            {
                vis[tx][ty] = true;
                t.x = tx;
                t.y = ty;
                t.step = s.step + 1;
                que.push(t);
            }
        }
    }

    return;
}
int main(void)
{
    while(scanf("%d%d%d", &h, &w, &n) != EOF)
    {
        for(int i = 0; i < h; i++)
            scanf("%s", map[i]);

        for(int i = 0; i < h; i++)
            for(int j = 0; j < w; j++)
            {
                if(map[i][j] == 'S')
                {
                    x[0] = i;
                    y[0] = j;
                }
                else if(map[i][j] >= '0' && map[i][j] <= '9')
                {
                    x[map[i][j] - '0'] = i;
                    y[map[i][j] - '0'] = j;
                }
            }

        result = 0;

        for(int i = 0; i < 9; i++)
        {
            BFS(x[i], y[i], i + 1);
        }

        printf("%d\n", result);
    }

	return 0;
}

C++: #include <vector>
#include <list>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <deque>
#include <algorithm>
#include <utility>
#include <functional>
#include <sstream>
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <ctime>
#include <climits>
#include <cassert>
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();}
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 EXIST(s,e) ((s).find(e)!=(s).end())
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n) FOR(i,0,n)
#define EACH(t,i,c) for(t::iterator i=(c).begin(); i!=(c).end(); ++i)
const double EPS = 1e-10;
const double PI  = acos(-1.0);

int dy[]={-1,0,1,0},dx[]={0,1,0,-1};
pii gp;

int bfs(vs &f,pii start,char goal,int h,int w){
	vvi cnt(h,vi(w,-1));
	queue<pii> q;
	q.push(start);
	cnt[start.first][start.second]=0;
	while(!q.empty()){
		pii p=q.front();q.pop();
		REP(d,4){
			int y=p.first+dy[d];
			int x=p.second+dx[d];
			if(y>=0&&x>=0&&y<h&&x<w&&f[y][x]!='X'){
				if(f[y][x]==goal){
					gp=make_pair(y,x);
					return cnt[p.first][p.second]+1;
				}else if(cnt[y][x]==-1){
					q.push(make_pair(y,x));
					cnt[y][x]=cnt[p.first][p.second]+1;
				}
			}
		}
	}
	assert(0);
}

int main(){
	int h,w,n;
	cin>>h>>w>>n;
	vs f(h);
	pii start;
	REP(i,h){
		cin>>f[i];
		REP(j,w){
			if(f[i][j]=='S')start=make_pair(i,j);
		}
	}
	pii cur=start;
	int cnt=0;
	FOR(i,1,n+1){
		cnt+=bfs(f,cur,'0'+i,h,w);
		cur=gp;
	}
	cout<<cnt<<endl;
}