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 <algorithm>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>
#include <cassert>
#include <iostream>
#include <map>
#include <queue>
#include <sstream>
#include <string>
#include <stack>
#include <set>
#include <vector>

using namespace std;

#define all(c) ((c).begin()), ((c).end())
#define dump(c) cerr << "> " << #c << " = " << (c) << endl;
#define iter(c) __typeof((c).begin())
#define tr(i, c) for (iter(c) i = (c).begin(); i != (c).end(); i++)
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define repi(i, a, b) for (int i = (int)(a); i <= (int)(b); i++)

#define mp make_pair
#define fst first
#define snd second
#define pb push_back

typedef unsigned int uint;
typedef long long ll;
typedef unsigned long long ull;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<double> vd;
typedef vector<vd> vvd;
typedef vector<string> vs;
typedef pair<int,int> pii;

const int INF = 1 << 29;
const double EPS = 1e-10;

template<typename T1,typename T2>
ostream& operator<<(ostream& os,const pair<T1,T2>& p){
    return os<<'('<<p.first<<','<<p.second<<')';
}
template<typename T>
ostream& operator<<(ostream& os,const vector<T>& a){
    os<<'[';
    rep(i,a.size()) os<<(i?" ":"")<<a[i];
    return os<<']';
}

typedef pair<int, pii> State;

int H, W, N;
char m[1010][1010];

vi bfs(int x, int y) {
	vi res(N + 1, 0);
	
	queue<pair<int, pii> > q;
	q.push(mp(0, mp(x, y)));
	map<pii, bool> visited;
	
	while(!q.empty()) {
		pair<int, pii> p = q.front();
		q.pop();
		if (visited[p.snd]) continue;
		visited[p.snd] = true;
		
		if (isdigit(m[p.snd.snd][p.snd.fst])) {
			res[m[p.snd.snd][p.snd.fst] - '0'] = p.fst;
		}
		if (m[p.snd.snd][p.snd.fst] == 'S') {
			res[0] = p.fst;
		}
		
		static const int dx[] = {1, 0, -1, 0};
		static const int dy[] = {0, 1, 0, -1};
		rep(d, 4) {
			int tx = p.snd.fst + dx[d];
			int ty = p.snd.snd + dy[d];
			if (tx < 0 || tx >= W || ty < 0 || ty >= H) continue;
			if (m[ty][tx] == 'X') continue;
			q.push(mp(p.fst + 1, mp(tx, ty)));
		}
	}
	
	return res;
}

int main() {
	cin >> H >> W >> N;
	pii start;
	rep(i, H) rep(j, W) {
		cin >> m[i][j];
		if (m[i][j] == 'S') {
			start.fst = j;
			start.snd = i;
		}
	}
	
	vvi mt(N + 1);
	rep(i, H) rep(j, W) {
		if (isdigit(m[i][j])) mt[m[i][j] - '0'] = bfs(j, i);
		else if (m[i][j] == 'S') mt[0] = bfs(j, i);
	}
	
	priority_queue<State, vector<State>, greater<State> > q;
	q.push(mp(0, mp(0, 0)));
	map<pii, bool> visited;
	
	while(!q.empty()) {
		State st = q.top();
		q.pop();
		if (visited[st.snd]) continue;
		visited[st.snd] = true;
		
		int pos = st.snd.snd;
		int ate = st.snd.fst;
		if (__builtin_popcount(ate) == N) {
			cout << st.fst << endl;
			break;
		}
		int hp = 1 + __builtin_popcount(ate);
		rep(i, N) if ((ate & 1 << i + 1) == 0) if (hp >= i + 1) {
			q.push(mp(st.fst + mt[pos][i + 1], mp(ate | 1 << i + 1, i + 1)));
		}
	}
    
    return 0;
}

C++: #include<cstdio>
#include<iostream>
#include<string>
using namespace std;
int flg[1000][1000],que[1000000][3];
char str[1000][1001]; 
int main(void){
	int i,j,k;
	int x,y,xx,yy,h,w,n,tai,p1,p2;
	int dx[4]={1,0,-1,0},dy[4]={0,1,0,-1};
	int min,max=1000000;
	cin>>h>>w>>n;
	for(i=0;i<=h;i++){
		for(j=0;j<=w;j++) flg[i][j]=1;
	}
	for(i=0;i<h;i++) cin>>str[i];
	for(i=0;i<h;i++){
		for(j=0;j<w;j++){
			if(str[i][j]=='S'){
				que[0][0]=i; que[0][1]=j; que[0][2]=0;
				flg[i][j]==0;
			}
		}	
	}
	tai=1; p1=0; p2=0;
	for(i=1;i<=n;i++){
		//cout<<i<<endl;
		if(p2>max) break;
		while(1){
			y=que[p1][0]; x=que[p1][1];
			if(str[y][x]-'0'==tai){
				tai++;
		//		printf("aaaaaaaa\n");
				for(j=0;j<h;j++){
					for(k=0;k<w;k++) flg[j][k]=max;
				}
				flg[y][x]==0;
				que[0][0]=y; que[0][1]=x; que[0][2]=que[p1][2];
				p1=0; p2=0;
				break;
			}
			for(j=0;j<4;j++){
				yy=y+dy[j]; xx=x+dx[j];
				if(yy>=0&&xx>=0&&yy<h&&xx<w&&str[yy][xx]!='X'&&flg[yy][xx]!=0){
					p2++;
					que[p2][0]=yy; que[p2][1]=xx; que[p2][2]=que[p1][2]+1;
					flg[yy][xx]=0;
				}
			}
			p1++;
			//printf("%d %d\n",p1,p2);
		}
		min=que[p1][2];
	}
	cout<<min<<endl;
	return 0;
}

C++: #include<iostream>
#include<cstdio>
#include<cstring>


const int INF = 0x3f3f3f3f;

using namespace std;

char maze[1010][1010];
int H, W, N;
int d[1010][1010];
int dx[4] = { 0,0,1,-1 }, dy[4] = { 1, -1, 0, 0 };
int sx[10], sy[10];
int ans = 0;

struct QNode
{
	int data_sx[1010];
	int data_sy[1010];
	int front, rear;
	int maxsize;
};
typedef struct QNode *Queue;

Queue Create()
{
	Queue Q;
	Q = (Queue)malloc(sizeof(struct QNode));
	Q->front = Q->rear = 0;
	Q->maxsize = 1010;
	return Q;
}
void push(Queue Q,int x,int y)
{
	if ((Q->rear + 1) % Q->maxsize == Q->front)
		return;
	Q->rear = (Q->rear + 1) % Q->maxsize;
	Q->data_sx[Q->rear] = x;
	Q->data_sy[Q->rear] = y;
}
int pop1(Queue Q)
{
	if (Q->front == Q->rear)
		return -1;
	Q->front = (Q->front + 1) % Q->maxsize;
	return Q->data_sx[Q->front];
}
int pop2(Queue Q)
{
	return Q->data_sy[Q->front];
}


void bfs(int i)
{
	Queue Q;
	Q = Create();
	memset(d, 0x3f, sizeof(d));
	push(Q, sx[i], sy[i]);
	d[sx[i]][sy[i]] = 0;
	if (i == N)
		return;
	while (Q->front != Q->rear)
	{
		int x = pop1(Q), y = pop2(Q);
		if (x == sx[i + 1] && y == sy[i + 1])
			return;

		for (int j = 0; j < 4; j++)
		{
			int nx = x + dx[j], ny = y + dy[j];
			if (nx >= 0 && nx < H && ny >= 0 && ny < W && d[nx][ny] == INF && maze[nx][ny]!='X')
			{
				push(Q, nx, ny);
				d[nx][ny] = d[x][y] + 1;
			}
		}
	}
}

void solve()
{
	for (int i = 0; i < H; i++)
	{
		for (int j = 0; j < W; j++)
		{
			if (maze[i][j] == 'S')
				sx[0] = i, sy[0] = j;
			else if (maze[i][j] >= '1'&&maze[i][j] <= '9')
				sx[maze[i][j] - '0'] = i, sy[maze[i][j] - '0'] = j;
		}
	}
	for (int i = 0; i < N; i++)
	{
		bfs(i);
		ans += d[sx[i + 1]][sy[i + 1]];
	}
	cout << ans << endl;
}

int main()
{
	cin >> H >> W >> N;

	for (int i = 0; i < H; i++)
		for (int j = 0; j < W; j++)
			cin >> maze[i][j];
	solve();
}