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<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#include<cmath>
#include<stack>
#include<queue>
#include<cctype>
#define INF 100000000
using namespace std;

struct  coor
{
	int x, y;
};

char map[1002][1002];
int time[1002][1002];
int vis[1002][1002];
int dx[4] = { 0,1,0,-1 };
int dy[4] = { 1,0,-1,0 };
int h, w, n;
coor s;
coor fac[9];
int phy;
int ans;


int bfs(coor fa)
{
	coor next;
	coor now;
	queue<coor>q;
	q.push(s);
	vis[s.x][s.y] = 1;
	while (!q.empty())
	{
		now = q.front();
		q.pop();
		if (now.x == fa.x&&now.y == fa.y)
		{
			break;
		}
		vis[now.x][now.y] = 1;
		for (int i = 0;i < 4;i++)
		{
			next.x = now.x + dx[i];
			next.y = now.y + dy[i];
			if (map[next.x][next.y] != 'X'&&next.x >= 0&& next.x < h &&next.y >= 0 && next.y < w&&!vis[next.x][next.y])
			{
				time[next.x][next.y] = time[now.x][now.y] + 1;
				q.push(next);
			}
		}
	}
	return time[fa.x][fa.y];
}

void timeinit(coor st)
{
	for (int i = 0;i < h;i++)
	{
		for (int j = 0;j < w;j++)
		{
			if (map[i][j] != 'X')
				time[i][j] = INF;
		}
	}
	time[st.x][st.y] = 0;

}
int main()
{
	while (~scanf("%d%d%d",&h,&w,&n))
	{
		getchar();
		for (int i = 0;i < h;i++)
		{
			for (int j = 0;j < w;j++)
			{
				scanf("%c", &map[i][j]);
				time[i][j] = INF;
				if (map[i][j] == 'S') { map[i][j] = '.';s.x = i;s.y = j; }
				if (isdigit(map[i][j]))
				{
					fac[map[i][j] - '0'].x = i;
					fac[map[i][j] - '0'].y = j;
				}
			}
			getchar();
		}

		phy = 1;
		time[s.x][s.y] = 0;
		ans = 0;
		for (int i = 1;i <= n;i++)
		{
			memset(vis, 0, sizeof(vis));
			ans += bfs(fac[i]);
			s.x = fac[i].x;
			s.y = fac[i].y;
			timeinit(s);
		}
		printf("%d\n", ans);
	}
	return 0;
}

C++: #include<stdio.h>
#include<iostream>
#include<queue>
using namespace std;
int m[1002][1002]={0},p[1002][1002]={0};
struct r{
int g,l,g2,l2;
};
int main(){
int h,w,n,i,j,a,b[2];
b[0]=1;
b[1]=-1;
char c[2001];
r gl;
queue<r> q;
cin>>h>>w>>n;
for(i=0;i<=h+1;i++){
m[i][0]=-1;
m[i][w+1]=-1;
}
for(i=0;i<=w+1;i++){
m[0][i]=-1;
m[h+1][i]=-1;
}
for(i=1;i<=h;i++){
	scanf("%s",c);
	for(j=1;j<=w;j++){
		a=c[j-1];
		if(a>=49&&a<=57){m[i][j]=a-48;}
		if(c[j-1]=='X'){m[i][j]=-1;}
		if(c[j-1]=='S'){
		gl.g=i;
		gl.g2=j;
		gl.l=0;
		gl.l2=1;
		q.push(gl);
		}
	}
}
while(!q.empty()){
	gl=q.front();
	q.pop();
	if(m[gl.g][gl.g2]==gl.l2){
		gl.l2++;
		if(gl.l2==n+1){
			break;
		}
		queue<r> q;
	}
	p[gl.g][gl.g2]=gl.l2;
gl.l++;
	for(i=0;i<2;i++){
		if(m[gl.g+b[i]][gl.g2]!=-1 && p[gl.g+b[i]][gl.g2]!=gl.l2){
			gl.g+=b[i];
			q.push(gl);
			gl.g-=b[i];
		}
		if(m[gl.g][gl.g2+b[i]]!=-1 && p[gl.g][gl.g2+b[i]]!=gl.l2){
			gl.g2+=b[i];
			q.push(gl);
			gl.g2-=b[i];
		}
	}
}
cout<<gl.l<<endl;
return 0;
}

C++: #include<iostream>
#include<queue>
#include<cstdio>
#include<cstring>
#include<utility>
using namespace std;
struct dir
{
	int x,y;
}dir[4]={{-1,0},{1,0},{0,-1},{0,1}};
char hole[1005][1005],factory[10][2];
int d[1005][1005],h,w;
typedef pair<int,int> P;
int bfs(int sx,int sy,int gx,int gy)
{
	for (int i = 0; i < h; i++)
	{
		for (int j = 0; j < w; j++)
		{
			d[i][j] = -1;
		}
	}
	//memset(d,-1,sizeof(d));
	queue<P> que;
	que.push(P(sx,sy));
	d[sx][sy]=0;
	while(que.size())
	{
		P p=que.front();
		que.pop();	
		if(p.first==gx&&p.second==gy)
		break;
		for(int i=0;i<4;i++)
		{
		int nx=p.first+dir[i].x;
		int ny=p.second+dir[i].y;
		if(nx>=0&&ny>=0&&nx<h&&ny<w&&hole[nx][ny]!='X'&&d[nx][ny]==-1)
		{
			d[nx][ny]=d[p.first][p.second]+1;
			que.push(P(nx,ny));
		}
		}
	}
	return d[gx][gy];
}
int main()
{
	int sx,sy,i,j,step=0,n;
	scanf("%d%d%d\n",&h,&w,&n);
	//cin>>h>>w>>n;
	for(i=0;i<h;i++,getchar())
		for(j=0;j<w;j++)
		{
			scanf("%c",&hole[i][j]);
			if(hole[i][j]=='S')
			{
				factory[0][0]=i;
				factory[0][1]=j;
			}
			if(isdigit(hole[i][j]))
			{
			factory[hole[i][j]-'0'][0]=i;
			factory[hole[i][j]-'0'][1]=j;
			}
		}
	for(i=0;i<n;i++)
	step+=bfs(factory[i][0],factory[i][1],factory[i+1][0],factory[i+1][1]);
	//cout<<step<<endl;
	printf("%d\n",step);
	return 0;
 }

C++: #include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#include<deque>
#include<map>
#include<set>
#include<string>
#include<sstream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<cctype>
#include<climits>
using namespace std;
#define REP(i, j) for(int i = 0; i < j; i++)
#define FOR(i, j, k) for(int i = j; i < k; i++)
#define P pair<int, int>
const int INF = INT_MAX / 2;

int h, w, n;

bool CanMove(int y, int x, vector< vector<char> > m){
    if(y < 0) return false;
    if(x < 0) return false;
    if(y >= h) return false;
    if(x >= w) return false;
    if(m[y][x] == 'X') return false;
    return true;
}

vector< vector<int> > MakeAnsMap(int y, int x, int step, vector< vector<int> > ans_map, vector< vector<char> > m){
    ans_map[y][x] = step;
    int my[] = {0, 0, 1, -1};
    int mx[] = {1, -1, 0, 0};

    REP(i, 4){
        int ny = y + my[i];
        int nx = x + mx[i];
        if(CanMove(ny, nx, m) && ans_map[ny][nx] > step + 1){
            ans_map = MakeAnsMap(ny, nx, step + 1, ans_map, m);
        }
    }
    return ans_map;
}

int main(){
    cin >>h >>w >>n;
    vector< vector<char> > m(h, vector<char>(w) );
    vector<int> y(n + 2), x(n + 2);

    //start of input
    REP(i, h){
        REP(j, w){
            cin >>m[i][j];
            if(m[i][j] == 'S'){
                y[0] = i;
                x[0] = j;
            }
            if(m[i][j] - '0' > 0 && m[i][j] - '0' <= n){
                int num = m[i][j] - '0';
                y[num] = i;
                x[num] = j;
            }
        }
    }
    //end of input

    vector< vector<int> > ans_map(h, vector<int>(w, INF) );
    ans_map = MakeAnsMap(y[0], x[0], 0, ans_map, m);

    FOR(i, 1, n + 1){
        int tmp = ans_map[y[i]][x[i]];
        REP(j, h){
            REP(k, w){
                ans_map[j][k] = INF;
            }
        }
        ans_map = MakeAnsMap(y[i], x[i], tmp, ans_map, m);

    }
    cout <<ans_map[y[n]][x[n]] <<endl;
    return 0;
}