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++: /*
 * main.cpp
 *
 *  Created on: 2015年10月21日
 *      Author: chen
 */
#include<stdio.h>
#include<iostream>
#include<string>
#include<string.h>
#include<algorithm>
#include<vector>
#include<time.h>
#include<queue>
#include<stack>
#include<iterator>
#include<math.h>
#include<stdlib.h>
#include<limits.h>
#include<memory.h>
//#define ONLINE_JUDGE
#define eps 1e-8
#define INF 0x7fffffff                                          //INT_MAX
#define inf 0x3f3f3f3f                                          //int??????????????????
#define FOR(i,a) for((i)=0;i<(a);(i)++)                          //[i,a);
#define MEM(a) (memset((a),0,sizeof(a)))
#define sfs(a) scanf("%s",a)
#define sf(a) scanf("%d",&a)
#define sfI(a) scanf("%I64d",&a)
#define pf(a) printf("%d\n",a)
#define pfI(a) printf("%I64d\n",a)
#define pfs(a) printf("%s\n",a)
#define sfd(a,b) scanf("%d%d",&a,&b)
#define sft(a,b,c)scanf("%d%d%d",&a,&b,&c)
#define for1(i,a,b) for(int i=(a);i<b;i++)
#define for2(i,a,b) for(int i=(a);i<=b;i++)
#define for3(i,a,b)for(int i=(b);i>=a;i--)
#define MEM1(a) memset(a,0,sizeof(a))
#define MEM2(a) memset(a,-1,sizeof(a))
#define LL __int64
const double PI = acos(-1.0);
template<class T> T gcd(T a, T b) { return b ? gcd(b, a % b) : a; }
template<class T> T lcm(T a, T b) { return a / gcd(a, b) * b; }
template<class T> inline T Min(T a, T b) { return a < b ? a : b; }
template<class T> inline T Max(T a, T b) { return a > b ? a : b; }
using namespace std;
template<class T>
T Mint(T a, T b, T c) {
	if (a>b) {
		if (c>b)
			return b;
		return c;
	}
	if (c>a)
		return a;
	return c;
}
template<class T>
T Maxt(T a, T b, T c) {
	if (a>b) {
		if (c>a)
			return c;
		return a;
	}
	else if (c > b)
		return c;
	return b;
}

const int maxn=1010;
int T,n,m;
int h,w;
char map[maxn][maxn];
bool vis[maxn][maxn];
int sx,sy,ex,ey;
int dx[]={-1,1,0,0};
int dy[]={0,0,1,-1};

struct node{
	int x,y;
	int t;
}aim[15];

bool judge(int x,int y){
	if(x<0||x>h||y<0||y>w)	return false;
	if(map[x][y]=='X') return false;
	if(vis[x][y]) return false;
	return true;
}

int bfs(){
	MEM1(vis);
	queue<node>q;
	node s,e;
	s.x=sx,s.y=sy,s.t=0;
	vis[s.x][s.y]=1;
	q.push(s);
	while(!q.empty()){
		s=q.front();
		//cout<<s.t<<endl;
		q.pop();
		if(s.x==ex&&s.y==ey){
			return s.t;
		}
		for(int i=0;i<4;i++){
			e.x=s.x+dx[i];
			e.y=s.y+dy[i];
			e.t=s.t+1;
			if(!judge(e.x,e.y))
				continue;
			q.push(e);
			vis[e.x][e.y]=1;
		}
	}
	return 0;
}

int main() {
	while(~sft(h,w,n)){
		getchar();
		for(int i=0;i<h;i++){
			for(int j=0;j<w;j++){
				scanf("%c",&map[i][j]);
				if(map[i][j]=='S'){
					sx=i;
					sy=j;
				}
				if(isdigit(map[i][j])){
					aim[map[i][j]-'0'].x=i;
					aim[map[i][j]-'0'].y=j;
				}
			}
			getchar();
		}
		aim[0].x=sx;aim[0].y=sy;
		int step=0;
		for(int i=0;i<n;i++){
			sx=aim[i].x;sy=aim[i].y;
			ex=aim[i+1].x;ey=aim[i+1].y;
			step+=bfs();
		}
		printf("%d\n",step);
	}
	return 0;
}

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

using namespace std;


vector<string> field;
pair<int,int> start;
pair<int,int> factory[10];
int h,w,n;

const int INF = 100000000;

// £Ì×ÚXg
int d[10][10];

// Ú®Ê
const int dy[] = {-1,0,0,1};
const int dx[] = {0,-1,1,0};

// ø«Å^¦çê½ê©çDæTõðs¤
void bfs(int idx){
	queue<pair<int,int> > *prv = new queue<pair<int,int> >();
	queue<pair<int,int> > *nxt = new queue<pair<int,int> >();

	// ÊßÏÝÌêði[
	bool passed[1001][1001];
	// falseÅú»
	for(int i = 0; i < 1001; i++)
		fill(passed[i],passed[i]+1001,false);
	// ÅÌê
	prv->push(factory[idx]);

	int dist = 0;
	// TõJn
	while(prv->size()){
		while(prv->size()){
			// ¡ñÌê
			pair<int,int> place = prv->front();prv->pop();
			if(passed[place.first][place.second]){
				continue;
			}

			//ÊßÏÝÉ·é
			passed[place.first][place.second] = true;

			// £ðXV
			if(field[place.first][place.second] == 'S'){
				d[idx][0] = dist;
			}
			else if(field[place.first][place.second] >= '0' && field[place.first][place.second] <= '9'){
				d[idx][field[place.first][place.second] - '0'] = dist;
			}

			// Ú®
			for(int i = 0; i < 4; i++){
				// Ú®æ
				pair<int,int> np = place;
				np.first += dy[i];
				np.second += dx[i];
				if(np.first >= 0 && np.second >= 0 && np.first < h && np.second < w){
					// áQ¨ÅÈ¢êAÚ®
					if(field[np.first][np.second] != 'X' && !passed[np.first][np.second]){
						nxt->push(np);
					}
				}
			}
		}
		dist++;
		// obt@¢ê©¦
		swap(prv,nxt);
	}
}



int main(){

	while(cin >> h >> w >> n){
		for(int i = 0; i < h; i++){
			string str;
			cin >> str;
			field.push_back(str);
			for(int j = 0; j < str.size(); j++){
				// X^[gn_ðL^µÄ¨­
				if(field[i][j] == 'S'){
					factory[0].first = i;
					factory[0].second = j;
				}
				// HêÌêðL¯
				else if(field[i][j] >= '1' && field[i][j] <= '9'){
					factory[field[i][j]-'0'] = make_pair(i,j);
				}
			}
		}
		for(int i = 0; i < 10; i++)
			fill(d[i],d[i]+10,INF);

		for(int i = 0; i <= n; i++){
			bfs(i);
		}

		vector<int> s;
		for(int i = 1; i <= n; i++)
			s.push_back(i);

		int minCost = INF;
		do{
			bool f = false;
			int sum = 0;
			for(int i = 0; i < s.size(); i++){
				if(s[i] <= i + 1){
					if(i == 0){
						sum += d[0][s[i]];
					}
					else{
						sum += d[s[i-1]][s[i]];
					}
				}
				else{
					f = true;
					break;
				}
			}
			if(!f){
				minCost = min(minCost,sum);
			}
		}while(next_permutation(s.begin(),s.end()));
		cout << minCost << endl;
	}

	return 0;
}