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 <cstdio>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;

int search(int sx, int sy, int dx, int dy, vector<vector<char> > &f, int w, int h)
{
vector<bool> visit;
queue<pair<pair<int, int>, int> > q;
visit.resize(w * h, false);
q.push_back(make_pair(make_pair(sx, sy), 0);
while(!q.empty()) {
int x = q.front().first.first;
int y = q.front().first.second;
int cost = q.front().second;
q.pop();
if(visit[x * w + y])
continue;
visit[x * w + y] = true;
if(f[x][y] == 'X')
continue;
if(x == dx && y == dy)
return cost;
int ix[4] = {-1, 0, 0, 1};
int iy[4] = {0, -1, 1, 0};
for(int i = 0; i < 4; ++i) {
int nx = ix[i] + x;
int ny = iy[i] + y;
if(nx < 0 || ny < 0 || nx >= w || ny >= h)
continue;
q.push(make_pair(make_pair(nx, ny), cost + 1));
}
}
return -1;
}

int main() {
int h, w, n;
vector<vector<char> > f;
vector<pair<int, int> pos;
scanf("%d%d%d", &h, &w, &n);
f.resize(h);
pos.resize(n + 1);
for(int i = 0; i < h; ++i) {
char temp[1024];
scanf("%s", temp);
f[i].resize(w);
for(int j = 0; j < w; ++j) {
f[i][j] = temp[j];
if(f[i][j] == 'S')
pos[0] = make_pair(i, j);
if('0' <= f[i][j] && f[i][j] <= '9')
pos[f[i][j] - '0'] = make_pair(i, j);
}
}
int ans = 0;
for(int i = 1; i <= n; ++i) {
int sx = pos[i - 1].first;
int sy = pos[i - 1].second;
int dx = pos[i].first;
int dy = pos[i].second;
ans += search(sx, sy, dx, dy, f, w, h);
}
printf("%d\n", ans);
return 0;
}

C++: #include <iostream>
#include <vector>
#include <list>
#include <algorithm>
#include <set>
#include <queue>
#include <stack>
#include <string>
#include <sstream>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>

#define rep(i, n) for(int i = 0; i < n; i ++)
#define COUNT(i, n) for(int i = 1; i <= n; i ++)
#define ITER(c) __typeof((c).begin())
#define each(c, it) for(ITER(c) it =(c).begin(); it!=(c).end(); it++)
#define ALL(c) c.begin(), c.end()
#define mp make_pair
#define pb push_back
#define MEMSET(v, h) memset((v), h, sizeof(v))
#define X first
#define Y second
#define P first
#define C second

using namespace std; 

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

const int INF = 1 << 24;
const int dx[] = {-1, 0, 1, 0};
const int dy[] = {0, -1, 0, 1};

int main(void){
    int w, h, n, res = 0; cin >> h >> w >> n;
    vs m(h);
    rep(y, h) cin >> m[y];
    pii s;
    rep(y, h) rep(x, w) if(m[y][x] == 'S') s = mp(x, y);

    rep(i, n){
        queue<mouse> q;
        q.push(mp(s, 0));

        vector< vector<bool> > used(h);
        rep(y, h) used[y].resize(w);

        while(!q.empty()){
            mouse cur = q.front();
            q.pop();

            if(used[cur.P.Y][cur.P.X]) continue;
            used[cur.P.Y][cur.P.X] = true;

            if(m[cur.P.Y][cur.P.X] == i + 1 + '0'){
                res += cur.C;
                s = mp(cur.P.X, cur.P.Y);
                break;
            }

            rep(i, 4){
                mouse next = mp(mp(cur.P.X + dx[i], cur.P.Y + dy[i]), cur.C + 1);
                if(0 <= next.P.X && next.P.Y < w &&
                   0 <= next.P.Y && next.P.Y < h &&
                   m[next.P.Y][next.P.X] != 'X') q.push(next);
            }
        }
    }

    cout << res << endl;

    return 0;
}

C++: #include<stdio.h>
#include<iostream>
using namespace std;
#include<queue>
int map[1002][1002]={0},myway[1002][1002]={0};
struct ALICE{
int t,h,x,y;
};
int main(){
int a,h,w,n,b,c,d,e,i,j,m=0,g[2],mark=0;
g[0]=1;
g[1]=-1;
char s[2002];
ALICE alice;
queue<ALICE> q;
cin>>h>>w>>n;
for(i=0;i<=h+1;i++){
map[i][0]=-1;
map[i][w+1]=-1;
}
for(i=0;i<=w+1;i++){
map[0][i]=-1;
map[h+1][i]=-1;
}
for(i=1;i<=h;i++){
	scanf("%s",s);
	for(j=0;j<=w;j++){
		a=s[j];
		if(a>48&&a<58)
			map[i][j+1]=a-48;
		else if(s[j]=='S'){
			alice.x=i;
			alice.y=j+1;
			alice.t=0;
			alice.h=1;
			q.push(alice);
		}
		else if(s[j]=='X')
			map[i][j+1]=-1;
	}
}
while(!q.empty()){
	alice=q.front();
	q.pop();
	if(map[alice.x][alice.y]==alice.h){
		alice.h++;
		mark=0;
		while(!q.empty()){
			q.pop();
		}
		for(i=1;i<=h;i++){
			for(j=1;j<=w;j++){
				myway[i][j]=0;
			}
		}
	}
	mark++;
	myway[alice.x][alice.y]=mark;
	if(alice.h==n+1){
		if(m==0||m>alice.t){
			m=alice.t;
			break;
		}
	}
	else{
	alice.t++;
		for(i=0;i<2;i++){
			if(map[alice.x+g[i]][alice.y]!=-1&&myway[alice.x+g[i]][alice.y]>mark||map[alice.x+g[i]][alice.y]!=-1&&myway[alice.x+g[i]][alice.y]==0){
				alice.x+=g[i];
				q.push(alice);
				alice.x-=g[i];
			}
			if(map[alice.x][alice.y+g[i]]!=-1&&myway[alice.x][alice.y+g[i]]>mark||map[alice.x][alice.y+g[i]]!=-1&&myway[alice.x][alice.y+g[i]]==0){
				alice.y+=g[i];
				q.push(alice);
				alice.y-=g[i];
			}
		}
	}
}
cout<<m<<endl;
return 0;
}

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

typedef pair<int, int> P;

int h, w;
const int dx[4] = {0, 0, -1, 1};
const int dy[4] = {-1, 1, 0, 0};
string field[1000];

int bfs(int& x, int& y, char goal) {
	queue<P> que;
	que.push(P(x, y));

	vector<vector<int> > d(h, vector<int>(w, -1));
	d[y][x] = 0;

	for(;;) {
		P s = que.front();
		que.pop();

		if(field[s.second][s.first] == goal) {
			x = s.first;
			y = s.second;
			return d[y][x];
		}

		for(int i = 0; i < 4; ++i) {
			int nx = s.first + dx[i], ny = s.second + dy[i];

			if(nx < 0 || ny < 0 || nx >= w || ny >= h)
				continue;

			if(field[ny][nx] == 'X' || d[ny][nx] != -1)
				continue;

			d[ny][nx] = d[s.second][s.first] + 1;
			que.push(P(nx, ny));
		}
	}
}

int main() {
	cin.tie(false);
	ios::sync_with_stdio(false);

	int n;
	cin >> h >> w >> n;

	for(int i = 0; i < h; ++i)
		cin >> field[i];

	int x, y;
	for(int i = 0; i < h; ++i) {
		for(int j = 0; j < w; ++j) {
			if(field[i][j] == 'S') {
				x = j;
				y = i;
				break;
			}
		}
	}

	int ans = 0;
	for(int i = 1; i <= n; ++i)
		ans += bfs(x, y, '0' + i);

	cout << ans << endl;

	return EXIT_SUCCESS;
}