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 <bits/stdc++.h>
using namespace std;
int H,W,N;
char Map[1010][1010];
int Si[10];
int Sj[10];
int ans=0;
typedef pair<int,int> P;
int dx[4]={1,0,-1,0};
int dy[4]={0,1,0,-1};
int dis[1010][1010];
int bfs(int i)
{
    memset(dis,-1,sizeof(dis));
    P S=make_pair(Si[i],Sj[i]);
    dis[Si[i]][Sj[i]] = 0;
    P E=make_pair(Si[i+1],Sj[i+1]);
    queue<P> q;
    q.push(S);
    while(q.size())
    {
        P next=q.front();
        q.pop();
        if(next.first==Si[i+1]&&next.second==Sj[i+1])
            break;
        for(int i=0;i<4;i++)
        {
            int nx=next.first+dx[i];
            int ny=next.second+dy[i];
            if(dis[nx][ny]<0&&nx>=1&&nx<=H&&ny>=1&&ny<=W&&Map[nx][ny]=='.')
            {
                q.push(P(nx,ny));
                dis[nx][ny]=dis[next.first][next.second]+1;
            }
        }
    }
    return dis[E.first][E.second];

}
int main()
{
    scanf("%d%d%d",&H,&W,&N);
    getchar();
    for(int i=1;i<=H;i++)
    {
        for(int j=1;j<=W;j++)
        {
            scanf("%c",&Map[i][j]);
            if(Map[i][j]=='S')
            {
                Si[0]=i;
                Sj[0]=j;
                Map[i][j]='.';
            }
            else if(isdigit(Map[i][j]))
            {
                Si[Map[i][j]-48]=i;
                Sj[Map[i][j]-48]=j;
                Map[i][j]='.';
            }
        }
        getchar();
    }
    for(int i=0;i<N;i++)
    {
        //cout<<i<<": "<<bfs(i)<<endl;
        ans+=bfs(i);
    }
    printf("%d\n",ans);


    return 0;
}

C++: #include<iostream>
#include<utility>
#include<vector>

using namespace std;

int H, W, N;
char mapT[1000][1000];
char temp_map[1000][1000];

int temp_x = 0, temp_y;
char temp;
int min_rou = 0;
int min_route = 500000;
int final_min_route = 0;
vector<pair<int, int> > dir;

void findSmallRoute(int x, int y, char &factory) {
	if (mapT[x][y] == factory) {
		++min_rou;
		if (min_route > (min_rou-1)) {
			min_route = min_rou - 1;
			temp_x = x;
			temp_y = y;
		}
		--min_rou;
		return;
	}
	if (x < 0 || y >= W || x >= H || y < 0 || mapT[x][y] == 'X') {
		return;
	}
	++min_rou;
	mapT[x][y] = 'X';
	for (vector<pair<int, int> >::iterator it = dir.begin(); it != dir.end(); ++it) {
		findSmallRoute(x + it->first, y + it->second, factory);
		
	}
	mapT[x][y] = temp_map[x][y];
	--min_rou;
	return;
}

int main() {
	dir.push_back({ -1,0 });
	dir.push_back({ 0,1 });
	dir.push_back({ 1,0 });
	dir.push_back({ 0,-1 });
	int start_X = 0, start_Y = 0;
	cin >> H >> W >> N;
	for (int i = 0; i < H; i++) {
		for (int j = 0; j < W; ++j) {
			cin >> temp;
			mapT[i][j] = temp;
			if (temp == 'S') {
				start_X = i;
				start_Y = j;
			}
		}
	}

	for (int i = 0; i < H; ++i) {
		for (int j = 0; j < W; ++j) {
			temp_map[i][j] = mapT[i][j];
		}
	}

	for (int factory = 1; factory != N + 1; ++factory) {
		
		char n = factory + '0';
		findSmallRoute(start_X, start_Y, n);
		for (int i = 0; i < H; ++i) {
			for (int j = 0; j < W; ++j) {
				mapT[i][j] = temp_map[i][j];
			}
		}
		final_min_route += min_route;
		min_rou = 0;
		min_route = 500000;
		
		start_X = temp_x;
		start_Y = temp_y;
	}

	cout << final_min_route << endl;
	system("pause");
	return 0;
}

C++: #include<iostream>
#include<cstdio>
#include<queue>
#include<map>
using namespace std;
typedef pair<unsigned short,unsigned short> P;
typedef pair<unsigned char,int> T;
typedef pair<T,P> PP;
#define rep(i,n) for(i=0;i<n;i++)
#define MAX 1000
char F[MAX][MAX];
char Dx[]={1,0,-1,0},Dy[]={0,1,0,-1};
unsigned short h,w,n,x,y,nx,ny;
P dist[10];
int bfs()
{
  bool used[9][MAX][MAX]={};
  int c,res=0,u=0;
  unsigned char t,i;
  PP p;
  queue<PP> q;
  rep(i,9)
    q.push(PP(T(i+'1',0),dist[i]));
  while(!q.empty()){
    p=q.front();
    q.pop();
    t=p.first.first;
    if(u&(1<<(t-'1')))continue;
    c=p.first.second;
    x=p.second.first;
    y=p.second.second;
    c++;
    rep(i,4){
      nx=x+Dx[i]; ny=y+Dy[i];
      if(nx<w&&ny<h&&F[ny][nx]!='X'&&!used[t-'1'][ny][nx]){
        used[t-'1'][ny][nx]=true;
        if(F[ny][nx]==t){
          u|=(1<<(t-'1'));
          res+=c;
        }
        else{
          q.push(PP(T(t,c),P(nx,ny)));          
        }
      }
    }
  }
  return res;
}
int main(void)
{
  unsigned short i,j;
  int res;
  scanf("%hd%hd%hd",&h,&w,&n);
  rep(i,h) rep(j,w){
    scanf(" %c",F[i]+j);
    if(F[i][j]=='S')
      dist[0]=P(j,i);
    else if(F[i][j]!='X'&&F[i][j]!='.')
      dist[F[i][j]-'0']=P(j,i);
  }
  res=bfs();
  printf("%d\n",res);
  return 0;

C++: #include<bits/stdc++.h>
using namespace std;
int solve(vector<vector<char>> vec,int h_start,int w_start,int h_end,int w_end){
	vector<int> nh = {1,0,-1,0};
	vector<int> nw = {0,1,0,-1};
	const int h_size = vec.size();
	const int w_size = vec[0].size();
	vector<vector<int>> depth(h_size,vector<int>(w_size,INT_MAX-1));
	depth[h_start][w_start] = 0;
	bool han[h_size][w_size] = {};
	queue<pair<int,int>> que;
	que.push(make_pair(h_start,w_start));
	while(que.size()){
		pair<int,int> now = que.front();
		que.pop();
		for(int i = 0;i < 4;i++){
			int next_h = now.first + nh[i];
			int next_w = now.second + nw[i];
			if(next_h < 0||next_w < 0||next_h >= h_size||next_w >= w_size)continue;
			if(vec[next_h][next_w] == 'X')continue;
			if(han[next_h][next_w] == true)continue;
			han[next_h][next_w] = true;
			depth[next_h][next_w] = depth[now.first][now.second] + 1;
			que.push(make_pair(next_h,next_w));
		}
	}
	return depth[h_end][w_end];
}
int main(){
	int h,w,n;
	cin >> h >> w >> n;
	vector<vector<char>> vec(h, vector<char>(w));
	for(int i = 0;i < h;++i){
		for(int j = 0;j < w;j++){
			cin >> vec[i][j];
		}
	}
	vector<int> basho_h(n + 1,0);
	vector<int> basho_w(n + 1,0);
	for(int i = 0;i < h;i++){
		for(int j = 0;j < w;j++){
			if(vec[i][j] == 'S'){
				basho_h[0] = i;
				basho_w[0] = j;
				//cout << i << j << endl;
			}
			if ('1' <= vec[i][j] && vec[i][j] <= '9') {
				basho_h[vec[i][j] - '0'] = i;
				basho_w[vec[i][j] - '0'] = j;
			}
		}
	}
	//cout << basho_h[0] << basho_w[0] << endl;
	int ans = 0;
	for(int i = 0;i < n;i++){
		ans += solve(vec,basho_h[i],basho_w[i],basho_h[i+1],basho_w[i+1]);
		//cout << ans << endl;
	}
	cout << ans << endl;
	return 0;
}