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 <vector>

const int MAX_SIZE = 1000;
char field[MAX_SIZE + 1][MAX_SIZE + 1];

const int STEP_NUM = 4;
const int STEP[STEP_NUM][STEP_NUM] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};

using Position = std::pair<int,int>;

const int MAXN = 10;
Position locations[MAXN];
 
int H, W, N;

int get_shortest_distance(int current_HP)
{
	int sx = locations[current_HP-1].first;
	int sy = locations[current_HP-1].second;
	int ex = locations[current_HP].first;
	int ey = locations[current_HP].second;

	bool is_visit[MAX_SIZE + 1][MAX_SIZE + 1]={};
	is_visit[sx][sy]=true;

	std::vector<Position> frontier(1,Position{sx,sy});
	for(int step=0;step<W*H;step++)
	{
		std::vector<Position> next_frontier;
		for(auto p:frontier)
			for(int i=0;i<STEP_NUM;i++)
			{
				int nx = p.first+STEP[i][0];
				int ny = p.second+STEP[i][1];
				if(nx==ex && ny==ey)	return step+1;
				if(nx<0 || H<=nx) 		continue;
				if(ny<0 || W<=ny) 		continue;
				if(field[nx][ny]=='X') 	continue;
				if(is_visit[nx][ny]) 	continue;
				next_frontier.push_back(std::make_pair(nx,ny));
				is_visit[nx][ny] = true;
			}
		frontier = next_frontier;
	}
	return -1;
}

int solve()
{
	int total_step = 0;
	for(int i=1;i<N+1;i++)
		total_step += get_shortest_distance(i);
	return total_step;
}

int main()
{
	scanf("%d %d %d", &H, &W, &N);
	for(int i=0; i<H; i++)
		scanf("%s", field[i]);
	for(int i=0; i<H; i++)
		for(int j=0; j<W; j++)
		{
			if(field[i][j]=='S')
				locations[0] = std::make_pair(i,j);
			if(isdigit(field[i][j]))
				locations[field[i][j]-'0'] = std::make_pair(i,j);
		}
	printf("%d\n", solve());
	return 0;
}

C++: #include<bits/stdc++.h>

using namespace std;
struct node
{
    int x, y, f;
} q[10000100];
char a[10100][10100];
int book[10100][10100];
int m, n, h, ans, head, tail;
int dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
void bfs(int x, int y, int step)
{
    if(h+1 == step)
        return ;
    memset(book, 0, sizeof(book));
    head = 0, tail = 1;
    book[x][y] = 1;
    q[head].x = x, q[head].y = y, q[head].f = 0;
    while(head < tail)
    {
        for(int i = 0; i < 4; i++)
        {
            q[tail].x = q[head].x + dir[i][0];
            q[tail].y = q[head].y + dir[i][1];
            q[tail].f = q[head].f+1;
            if(a[q[tail].x][q[tail].y] == 'X' || book[q[tail].x][q[tail].y] || q[tail].x >= m || q[tail].x < 0 || q[tail].y >= n || q[tail].y < 0)
                continue;
            book[q[tail].x][q[tail].y] = 1;
            if(a[q[tail].x][q[tail].y] == step + '0')
            {
                ans += q[tail].f;
                bfs(q[tail].x, q[tail].y, step+1);
            }
            tail++;
        }
        head++;
    }
}
int main ()
{
    while(~scanf("%d %d %d", &m, &n, &h))
    {
        int i, j;
        ans = 0;
        for(i = 0; i < m; i++)
            scanf("%s", a[i]);
        for(i = 0; i < m; i++)
            for(j = 0; j < n; j++)
                if(a[i][j] == 'S')
                    bfs(i, j, 1);
        printf("%d\n", ans);
    }
    return 0;
}

C++: #include<cstdio>
#include<queue>
#include<algorithm>
#define INF 1000000
using namespace std;
typedef pair<int,int> P;
int h,w,n,ans=0;
bool map[1002][1002];
int x[10],y[10];
int dx[4]={0,1,0,-1};
int dy[4]={-1,0,1,0};
int main(){
    scanf("%d %d %d",&h,&w,&n);
    fill(map[0],map[0]+1002*1002,false);
    for(int i=1;i<=h;i++){
        getchar();
        for(int j=1;j<=w;j++){
            char c=getchar();
            if(c!='X'){
                map[i][j]=true;
                if(c=='S'){
                    x[0]=i;
                    y[0]=j;
                }else if(c!='.'){
                    x[c-48]=i;
                    y[c-48]=j;
                }
            }
        }
    }
    for(int i=0;i<n;i++){
        int d[1002][1002];
        fill(d[0],d[0]+1002*1002,INF);
        queue<P> q;
        d[x[i]][y[i]]=0;
        q.push(P(x[i],y[i]));
        while(!q.empty()){
            P p=q.front();
            int sx=p.first;
            int sy=p.second;
            q.pop();
            if(sx==x[i+1]&&sy==y[i+1]) break;
            for(int j=0;j<4;j++){
                if(map[sx+dx[j]][sy+dy[j]]&&d[sx+dx[j]][sy+dy[j]]==INF){
                    d[sx+dx[j]][sy+dy[j]]=d[sx][sy]+1;
                    q.push(P(sx+dx[j],sy+dy[j]));
                }
            }
        }
        ans+=d[x[i+1]][y[i+1]];
    }
    printf("%d\n",ans);
}

C++: #include<iostream>
#include<queue>
#include<cctype>
#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,n;
typedef pair<int,int> P;
int bfs(const int &sx,const int &sy,const int &gx,const 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)
		{
			que.push(P(nx,ny));
			d[nx][ny]=d[p.first][p.second]+1;
		}
		}
	}
	return d[gx][gy];
}
int main()
{
	//scanf("%d%d%d\n",&h,&w,&n);
	cin>>h>>w>>n;
	for(int i=0;i<h;i++)
		for(int j=0;j<w;j++)
		{
			//scanf("%c",&hole[i][j]);
			cin >> hole[i][j];
			if(hole[i][j]=='S')
			{
				factory[0][0]=i;
				factory[0][1]=j;
			}
			if(isdigit(hole[i][j]))
			{
				int index=hole[i][j]-'0';
			factory[index][0]=i;
			factory[index][1]=j;
			}
		}
	int step=0;
	for(int 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;
 }