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<queue>
#include<cctype>
#include<cstdio>

#define	mp			make_pair
#define	rep(i,n)	for(int i=0;i<n;i++)

using namespace std;

typedef	pair<int,int>	pii;

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

int h,w;
char grid[1000][1001];

int shortestDistance(int sx,int sy,int gx,int gy){
	static bool visited[1000][1000];
	rep(i,h)rep(j,w)	visited[i][j]=false;
	visited[sy][sx]=true;

	queue< pair<int,pii> > qu;	qu.push(mp(0,mp(sx,sy)));
	while(1){
		pair<int,pii> a=qu.front();	qu.pop();
		int d=a.first,x=a.second.first,y=a.second.second;
		if(x==gx && y==gy)	return d;

		rep(i,4){
			int xx=x+dx[i],yy=y+dy[i];
			if(0<=xx && xx<w && 0<=yy && yy<h && grid[yy][xx]!='X' && !visited[yy][xx]){
				visited[y][x]=true;
				qu.push(mp(d+1,mp(xx,yy)));
			}
		}
	}
}

int main(){
	int n;	scanf("%d%d%d",&h,&w,&n);
	int cx[10],cy[10];
	rep(i,h){
		scanf("%s",grid[i]);
		rep(j,w){
			if(grid[i][j]=='S')		cx[0]=j,cy[0]=i;
			if(isdigit(grid[i][j]))	cx[grid[i][j]-'0']=j,cy[grid[i][j]-'0']=i;
		}
	}

	int cost=0;
	rep(i,n)	cost+=shortestDistance(cx[i],cy[i],cx[i+1],cy[i+1]);
	printf("%d\n",cost);

	return 0;
}

C++: #include<iostream>
#include<algorithm>
#include<queue>

using namespace std;

int h, w, n;

char map[1001][1001];

int vis[1001][1001];

const int v[2][4] = { {1,0,-1,0},{0,-1,0,1} };

queue<pair<int ,int> > Pos;
queue <pair<int, pair< int, int > > > que;


int main() {
	cin >> h >> w >> n;
	for (int i = 1; i <= h; i++) {
		for (int j = 1; j <= w; j++) {
			cin >> map[i][j];
			if (map[i][j] == 'S')que.push(make_pair(0,make_pair(i,j)));
		}
	}
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= h; j++) {
			for (int k = 1; k <= w; k++) {
				if (map[j][k] - '0' == i)Pos.push(make_pair(j,k));
			}
		}
	}
	int ct = 0;
	while (Pos.size()) {
		pair<int, int > P = Pos.front();
		Pos.pop();
		while (que.size()) {
			pair<int,pair< int,int > > a = que.front();
			que.pop();
			if (vis[a.second.first][a.second.second] != 0)continue;
			vis[a.second.first][a.second.second] = a.first + 1;
			if (a.second.first == P.first&&a.second.second == P.second) {
				ct += vis[a.second.first][a.second.second];
				for (int i = 1; i <= h; i++) {
					for (int j = 1; j <= w; j++) {
						vis[i][j] = 0;
					}
				}
				while (que.size())que.pop();
				if(Pos.size())que.push(make_pair(0,make_pair(a.second.first,a.second.second)));
				ct -= 1;
				break;
			}
			for (int i = 0; i < 4; i++) {
				int px= a.second.first + v[0][i], py= a.second.second + v[1][i];
				if (1 <= px&&px <= h && 1 <= py&&py <= w&&vis[px][py] == 0 && map[px][py] != 'S'&&map[px][py]!='X') {
					que.push(make_pair(vis[a.second.first][a.second.second], make_pair(px, py)));
				}
			}
		}
	}
	cout << ct << endl;
	return 0;
}

C++: #include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <set>
#include <map>
#include <string>
#include <stack>
#include <queue>
#include <cmath>
#include <cstdio>
#include <istream>
#include <sstream>
#include <iomanip>
#include <iterator>
#include <climits>
using namespace std;

typedef ostringstream OSS;
typedef istringstream ISS;

typedef vector<int> VI;
typedef vector< VI > VVI;

typedef long long LL;

typedef pair<int, int> PII;
typedef vector<PII> VPII;

#define Y first
#define X second

int H, W, N;
vector<string> ts;

int main(void) {
	cin >> H >> W >> N;
	ts = vector<string>(H);
	for (auto &line : ts) cin >> line;

	string seq(N, '0');
	iota(seq.begin(), seq.end(), '1');
	
	PII start;
	for (int y = 0; y < H; y++) {
		for (int x = 0; x < W; x++) {
			if (ts[y][x] == 'S') {
				start.Y = y;
				start.X = x;
			}
		}
	}

	int total_time = 0;
	queue<pair<int, PII>> q;
	q.push(make_pair(0, start));
	vector<vector<bool>> done(H, vector<bool>(W));

	for (int i = 0; i < N; i++) {
		while(q.size()) {
			int now = q.front().first;
			int y = q.front().second.Y;
			int x = q.front().second.X;
			q.pop();

			if (done[y][x]) continue;
			done[y][x] = true;

			if (ts[y][x] == seq[i]) {
				q = queue<pair<int, PII>>();
				q.push(make_pair(0, make_pair(y, x)));
				done = vector<vector<bool>>(H, vector<bool>(W));
				total_time += now;
				break;
			}

			for (int dx = -1; dx <= 1; dx++) {
				for (int dy = -1; dy <= 1; dy++) {
					if (!(!dx ^ !dy)) continue;
					int nx = x + dx;
					int ny = y + dy;

					if (nx < 0 || ny < 0 || nx >= W || ny >= H) continue;
					if (done[ny][nx]) continue;
					if (ts[ny][nx] == 'X') continue;

					if (!done[ny][nx]) {
						q.push(make_pair(now + 1, make_pair(ny, nx)));
					}
				}
			}
		}
	}

	cout << total_time << endl;
	

	return 0;
}