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 <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);

		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;
}

C++: #include<stdio.h>
#include<iostream>
#include<queue>
using namespace std;
struct k{
	int x,y,c;
};
queue<k> q;
int p[1002][1002],m[1002][1002];
int main(void) {
	k z,z1;
	char d;
	int v=1,h,w,n,i,j,dx[4]={1,0,-1,0},dy[4]={0,1,0,-1};
	cin >> h >> w>>n;
	for (i = 0; i != w + 2; i++) {
		for (j = 0; j != h + 2; j++){
			p[j][i] = 99;
			m[j][i]=0;
		}
	}for (i = 1; i != w + 1; i++) {
		for (j = 1; j != h + 1; j++){
			m[j][i]=99;
		}
	}
	for (i = 1; i <= h; i++) {
		for (j = 1; j <= w; j++){
			cin >> d;
			switch(d){
				case 'S':
					z.x=j;
					z.y=i;
					z.c=0;
					p[i][j]=-1;
					break;
				case '.':
					p[i][j]=-1;
					break;
				case 'X':
					p[i][j]=99;
					break;
				case '1':
					p[i][j]=1;
					break;
				case '2':
					p[i][j]=2;
					break;
				case '3':
					p[i][j]=3;
					break;
				case '4':
					p[i][j]=4;
					break;
				case '5':
					p[i][j]=5;
					break;
				case '6':
					p[i][j]=6;
					break;
				case '7':
					p[i][j]=7;
					break;
				case '8':
					p[i][j]=8;
					break;
				case '9':
					p[i][j]=9;
					break;
			}
		}
	}
	q.push(z);
	while(!q.empty()){
			z=q.front();
			q.pop();
			if(m[z.y][z.x]==v)
				continue;
			if(p[z.y][z.x]==v){
				if(p[z.y][z.x]==n)
					break;
				while(!q.empty())
					q.pop();
				q.push(z);
				v++;
				printf("%d %d %d\n",z.x,z.y,z.c);
			}
		//	cout<<p[z.y][z.x]<<" "<<z.y<<" "<<z.x<<endl;
			m[z.y][z.x]=v;
			for(i=0;i!=4;i++){
				if(p[z.y+dy[i]][z.x+dx[i]]!=99/*&&z.x+dx[i]!=v&&z.y+dy[i]!=v*/){
					z1.x=z.x+dx[i];
					z1.y=z.y+dy[i];
					z1.c=z.c+1;
					q.push(z1);
				}
			}
	}
	cout <<z.c<< endl;
}

C++: #include<cstdio>
#include<cstring>
#include<queue>
#include<vector>
#include<algorithm>
#include<cmath>
using namespace std;

int n,m,l,cnt,mx,my;
char a[1009][1009];
int vis[1009][1009];
pair<int,int> p[10],st;
int mov[4][2] = {1,0,0,-1,-1,0,0,1};
struct status
{
    int x,y;
    int ord;
    int fx;
    status(int a=0,int b=0,int c=0,int s=0)
    {
        x = a, y = b, ord = c, fx = s;
    }
    bool operator < (struct status t) const
    {
        if(ord != t.ord) return ord > t.ord;
        else return fx > t.fx;
    }
}tt[4];

void bfs(int x,int y,int color)
{
    queue <struct status> q;
    struct status temp(x,y,0,fabs(x-p[color].first) + fabs(y - p[color].second));
    q.push(temp);
    int flag = 0;
    while(!q.empty())
    {
        struct status nw = q.front();
        q.pop();
        if(nw.x == p[color].first && nw.y == p[color].second)
        {
            cnt += nw.ord;
            break;
        }
        vis[nw.x][nw.y] = 1;
        int cct = 0;
        for(int i=0;i<4;i++)
        {
            int tx = mov[i][0] + nw.x, ty = nw.y + mov[i][1];
            if(tx>=0 && tx< n && ty>=0 && ty< m && !vis[tx][ty] && a[tx][ty] != 'X')
            {
                struct status tmp(tx,ty,nw.ord+1,fabs(tx-p[color].first) + fabs(ty - p[color].second));
                tt[cct++] = tmp;
                vis[tx][ty] = 1;
            }
        }
        sort(tt,tt+cct);
        for(int i=0;i<cct;i++) q.push(tt[i]);
    }
}

int main()
{
    while(~scanf("%d%d%d",&n,&m,&l))
    {
        getchar();
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<m;j++)
            {
                scanf("%c",&a[i][j]);
                if(a[i][j]>='0' && a[i][j]<='9')
                    p[a[i][j]-'0'].first = i, p[a[i][j]-'0'].second = j;
                if(a[i][j] == 'S') st.first = i, st.second = j;
            }
            getchar();
        }

        int sx = st.first, sy = st.second;
        cnt = 0;
        for(int i=1;i<=l;i++)
        {
            memset(vis,0,sizeof(vis));
            bfs(sx,sy,i);
            sx = p[i].first, sy = p[i].second;
        }
        printf("%d\n",cnt);
    }
    return 0;
}