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 <set>
#include <iostream>

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

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

const int MAXN = 10;
int locationsX[MAXN];
int locationsY[MAXN];
 
int H, W, N;

int get_shortest_distance(int current_HP)
{
	int sx = locationsX[current_HP-1];
	int sy = locationsY[current_HP-1];
	int ex = locationsX[current_HP];
	int ey = locationsY[current_HP];

	bool is_visit[H + 1][W + 1]={};
	/*
	for(int i=0;i<H;i++)
		for(int j=0;j<W;j++)
			is_visit[i][j]=false;
	*/
	std::set<std::pair<int,int>> frontier;
	frontier.insert(std::pair<int,int>{sx,sy});
	int nx,ny;
	for(int step=0;step<100000000;step++)
	{
		for(auto p:frontier)
		{
			if(p.first==ex && p.second==ey)	return step;
			is_visit[p.first][p.second] = true;
		}
		std::set<std::pair<int,int>> next_frontier;
		for(auto p:frontier)
		{
			for(int i=0;i<STEP_NUM;i++)
			{
				nx = p.first+STEP[i][0];
				ny = p.second+STEP[i][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.insert(std::make_pair(nx,ny));
			}
		}
		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++)
		{
			int HP=-1;
			if(field[i][j]=='S')	HP=0;
			if(field[i][j]=='1')	HP=1;
			if(field[i][j]=='2')	HP=2;
			if(field[i][j]=='3')	HP=3;
			if(field[i][j]=='4')	HP=4;
			if(field[i][j]=='5')	HP=5;
			if(field[i][j]=='6')	HP=6;
			if(field[i][j]=='7')	HP=7;
			if(field[i][j]=='8')	HP=8;
			if(field[i][j]=='9')	HP=9;
			if(HP!=-1)
			{
				locationsX[HP]=i;
				locationsY[HP]=j;
			}
		}
	printf("%d\n", solve());
	return 0;
}

C++: //http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0558
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;

int row, col, n;

struct point {
	int x, y;
};

char map[1010][1010];
int d[1010][1010];
int direct[4][2] = { {0,1},{0,-1},{1,0},{-1,0} };

int BFS(int &startX, int &startY, char target) {
	memset(d,0,sizeof(d));

	queue<point> q;
	point p;
	p.x = startX;
	p.y = startY;
	d[startX][startY] = 0;
	q.push(p);
	while (!q.empty()) {
		int nowX = q.front().x,nowY = q.front().y;
		q.pop();

		if (map[nowX][nowY] == target) {
			startX = nowX;
			startY = nowY;
			return d[nowX][nowY];
		}

		int nextX, nextY;
		for (int i = 0; i < 4; i++) {
			nextX = nowX + direct[i][0];
			nextY = nowY + direct[i][1];

			if (nextX >= 0 && nextY >= 0 && nextX < row && nextY < col && 
					map[nextX][nextY] != 'X' && d[nextX][nextY] == 0) {
				d[nextX][nextY] = d[nowX][nowY] + 1;
				p.x = nextX;
				p.y = nextY;
				q.push(p);
			}
		}
	}
	return -1;
}

int main() {
	int startX, startY, sum = 0;

	scanf("%d%d%d", &row, &col, &n);
	for (int i = 0; i < row; i++) {
		scanf("%s", map[i]);
		for (int j = 0; j < col; j++) {
			if (map[i][j] == 'S') {
				startX = i;
				startY = j;
			}
		}
	}

	for (int i = 0; i < n; i++) {
		int dis = BFS(startX, startY, i + '1');
		sum += dis;
	}
	printf("%d\n", sum);
}

C++: #include <iostream>
#include <queue>
#define INF 300000

using namespace std;

typedef pair<int, int> p;

int w, h, n, result, steps;
int visited[1000][1000];
bool map[1000][1000];
p start, last_start, goal, cur, cheese[10];
queue<p> myqueue;

void init(int in){
    start = last_start;

    while(!myqueue.empty()) myqueue.pop();

    for(int i=0; i<w; ++i){
        for(int j=0; j<h; ++j){
            if(map[i][j] == false){
                visited[i][j] = -1;
            }else{
                visited[i][j] = INF;
            }
            goal = cheese[in];
        }
    }
    /*for(int i=0; i<w; ++i){
        for(int j=0; j<h; ++j){

            cout << visited[i][j] << " ";

        }
        cout << endl;
    }*/

    return ;
}

int main(){
    cin >> w >> h >> n;

    char input;
    for(int i=0; i<w; ++i){
        for(int j=0; j<h; ++j){
            cin >> input;
            if(input == 'X') map[i][j] = false;
            else             map[i][j] = true;
            if(input == 'S')
                last_start = make_pair(i, j);
            if(input != 'X' && input != 'S' && input != '.'){
                cheese[input-'0'] = make_pair(i, j);
            }
        }
    }


    result = 0;
    for(int i=1; i<=n; ++i){
        init(i);
        myqueue.push(start);
        visited[start.first][start.second] = 0;

        while(!myqueue.empty()){

            /*for(int k=0; k<w; ++k){
                for(int j=0; j<h; ++j){

                    cout << visited[k][j] << " ";

                }
                cout << endl;
            }
            cout << endl;*/

            cur = myqueue.front();
            myqueue.pop();

            if(cur == goal){
                //cout << "goal " << cur.first << " , " << cur.second << "\n";
                break;
            }

            //visited[cur.first][cur.second] = 0;

            int x = cur.first, y = cur.second;
            if(x-1 >= 0 && visited[x-1][y]==INF){
                myqueue.push(make_pair(x-1, y));
                visited[x-1][y] = visited[x][y]+1;
            }
            if(y-1 >= 0 && visited[x][y-1]==INF){
                myqueue.push(make_pair(x, y-1));
                visited[x][y-1] = visited[x][y]+1;
            }
            if(x+1 < w && visited[x+1][y]==INF){
                myqueue.push(make_pair(x+1, y));
                visited[x+1][y] = visited[x][y]+1;
            }
            if(y+1 < h && visited[x][y+1]==INF){
                myqueue.push(make_pair(x, y+1));
                visited[x][y+1] = visited[x][y]+1;
            }
        }

        result += visited[goal.first][goal.second];
        //cout << visited[goal.first][goal.second] << endl;
        last_start = goal;
    }

    cout << result << endl;
    return 0;
}