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 <queue>
//aoj 0558 广度优先搜索
#define M_VALUE 10000000
using namespace std;
//定义四个方向
int H, W, N;

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

//用于存储迷宫
char map[1024][1024];

//用于存储距离
int d[1024][1024];

int factory[16][2];

typedef pair<int, int> P;

//采用广度优先遍历，寻找从(sx,sy)到(ex,ey)的最短路径
int bfs(int sx, int sy, int ex, int ey) {
    queue<P> que;

    for (int i = 0; i < H; i++) {
        for (int j = 0; j < W; j++) {
            d[i][j] = M_VALUE;
        }
    }
    que.push(P(sx, sy));
    d[sx][sy] = 0;
    while (que.size()) {
        P p = que.front();
        que.pop();

        if (p.first == ex && p.second == ey) {
            break;
        }

        for (int i = 0; i < 4; i++) {
            int nx = p.first + dir[i][0];
            int ny = p.second + dir[i][1];


            if (nx >= 0 && ny >= 0 && nx < H && ny < W && d[nx][ny] == M_VALUE && map[nx][ny] != 'X') {
                que.push(P(nx, ny));
                d[nx][ny] = d[p.first][p.second] + 1;
            }

        }


    }
    return d[ex][ey];

}

int main() {
    cin >> H >> W >> N;
    for (int i = 0; i < H; i++) {
        for (int j = 0; j < W; j++) {
            cin >> map[i][j];
            if (map[i][j] == 'S') {
                factory[0][0] = i;
                factory[0][1] = j;
            }
            if (isdigit(map[i][j])) {
                int index = map[i][j] - '0';
                factory[index][0] = i;
                factory[index][1] = j;
            }
        }
    }
    int res = 0;

    for (int i = 0; i < N; i++) {
        res += bfs(factory[i][0], factory[i][1], factory[i + 1][0], factory[i + 1][1]);
    }
    cout << res << endl;

    return 0;
}

C++: #include <iostream>
#include <queue>
#include <algorithm>
#define N 1002
#define INFINITY 2000000000
using namespace std;
void bfs();
int h,w,n,num[N][N],d[N*N],u,m,x=1;
string color[N*N],in[N*N];
int main(){
  int i,j,k;
  cin >> h >> w >> n;
  for(i=0;i<h+2;i++)
    for(j=0;j<w+2;j++)
      num[i][j]=-1;
  for(i=1;i<=h;i++) cin >> in[i],in[i]='X'+in[i];
  k=0;
  for(i=1;i<=h;i++){
    for(j=1;j<=w;j++){
      if(in[i][j]!='X') num[i][j]=k,k++;
    }
  }
  bfs();
  return 0;
}
void bfs(){
  int i,j,p=1,t=0,flag=0;
  char start='S',goal='1';
  queue<int> q;
  while(1){
    if(flag==1) start=x+'0',goal=x+'0'+1,x++;
    if(x>n+1) break;
    for(i=1;i<=h;i++){
      for(j=1;j<=w;j++){
	color[num[i][j]]="WHITE",d[num[i][j]]=INFINITY;
      }
    }
    for(i=1;i<=h;i++){
      for(j=1;j<=w;j++){
	if(in[i][j]==start) color[num[i][j]]="GLAY",d[num[i][j]]=0,q.push(num[i][j]);
      }
    }
    while(q.empty()!=1){
      u=q.front();
      q.pop();
      for(i=1;i<=h;i++){
	for(j=1;j<=w;j++){
	  if(num[i][j]!=-1&&(num[i-1][j]==u||num[i+1][j]==u||num[i][j+1]==u||num[i][j-1]==u)&&color[num[i][j]]=="WHITE"){
	    color[num[i][j]]="GLAY";
	    d[num[i][j]]=d[u]+1;
	    q.push(num[i][j]);
	  }
	}
      }
      color[u]="BLACK";
    }
    for(i=1;i<=h;i++){
      for(j=1;j<=w;j++){
	if(in[i][j]==goal) t+=d[num[i][j]];
      }
    }
    flag=1;
  }
  cout << t << endl;
}

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

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);
		//  éX^[gn_Ü½ÍHê©çÊÌHêÖÌÅZ£ðDæTõÅßé
		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;
}