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<iostream>  
#include<queue>  
using namespace std;  
#define INF 1000  
int H, W, N;  
char map[1001][1001];  
int dx[4] = { 0, 0, 1, -1 };  
int dy[4] = { 1, -1, 0, 0 };  
int d[1001][1001];  
int sx, sy;  
int gx, gy;  
typedef pair<int, int> P;  
int sum = 0;  
void bfs()  
{  
    queue<P> que;  
    for (int i = 0; i < H; i++)  
        for (int j = 0; j < W; j++)  
            d[i][j] = INF;  
    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 + dx[i], ny = p.second + dy[i];  
            if (0 <= nx&&nx < H && 0 <= ny&&ny < W&&map[nx][ny] != 'X'&&d[nx][ny] == INF)  
            {  
                que.push(P(nx, ny));  
                d[nx][ny] = d[p.first][p.second] + 1;  
            }  
        }  
    }  
    sum+=d[gx][gy];  
  
}  
int main()  
{  
    scanf("%d%d%d", &H, &W, &N);  
    while (getchar() != '\n')continue;  
    for (int i = 0; i < H; i++){  
        gets(map[i]);  
    }  
    for (int i = 0; i < H; i++)  
        for (int j = 0; j < W; j++)  
        {  
        if (map[i][j] == 'S')  
        {  
            sx = i;  
            sy = j; 
        }  
        }  
  
  
  
  
    for (int i = 0; i < N; i++)  
    {  
        for (int j = 0; j < H; j++)  
        {  
            for (int k = 0; k < W; k++)  
            {  
                if (map[j][k] == '1' + i)  
                {  
                      
                    gx = j; gy = k;  
                    bfs();
                    sx = j; sy = k;  
                }  
                      
            }  
        }  
    }  
    printf("%d\n", sum);  
  
}

C++: #include <iostream>
#include <cstring>
#include <queue>
#include <algorithm>
#include <cstdio>

#define INF 1 << 29

using namespace std;

int dx[4] = {1,0,-1,0};
int dy[4] = {0,-1,0,1};
char f[1003][1003];
bool visited[1003][1003][10];

class S{
public:
    int x;
    int y;
    int lvl;
    int step;

    S(int x, int y, int lvl, int step):x(x),y(y),lvl(lvl),step(step){}
};

int main(){
    int h,w,lvl,sx,sy,gx,gy;
    cin >> h >> w >> lvl;
    fill((char *)f, (char *)f+1003*1003, 'X');
    fill((bool *)visited, (bool *)visited+1003*1003*10, false);

    for(int i=1;i<=h;i++){
        for(int j=1;j<=w;j++){
            cin >> f[i][j];
            if(f[i][j] == 'S'){
                sx = j;
                sy = i;
            }else if(f[i][j] == lvl + '0'){
                gx = j;
                gy = i;
            }
        }
    }
    deque<S> q;
    q.push_back(S(sx,sy,1,0));
    visited[sy][sx][1] = true;
    int px,py,tmplvl,tmpstep;
    while(!q.empty()){
        px = q.front().x;
        py = q.front().y;
        tmplvl = q.front().lvl;
        tmpstep = q.front().step;
        q.pop_front();

        //printf("current:(y = %d, x = %d, lvl = %d, step = %d)\n", py,px,tmplvl,tmpstep);

        if(py == gy && px == gx && tmplvl == lvl+1){
            break;
        }
        visited[py][px][tmplvl] = tmpstep;
        for(int i=0;i<4;i++){
            int nx = px + dx[i];
            int ny = py + dy[i];

            if(f[ny][nx] != 'X'){
                if(f[ny][nx] == tmplvl +'0'){
                    q.push_back(S(nx,ny,tmplvl+1,tmpstep+1));
                }else{
                    if(!visited[ny][nx][tmplvl]){
                        q.push_back(S(nx,ny,tmplvl,tmpstep+1));
                        visited[ny][nx][tmplvl] = true;
                    }
                }
            }
        }
    }
    cout << tmpstep << endl;
}

C++: #include <cstdio>
#include <set>
#include <vector>
#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[MAX_SIZE + 1][W + 1]={};
	bool is_visit[MAX_SIZE + 1][MAX_SIZE + 1]={};

//	std::set<std::pair<int,int>> frontier;
//	frontier.insert(std::pair<int,int>{sx,sy});
	std::vector<std::pair<int,int>> frontier;
	frontier.push_back(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;
		std::vector<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));
				next_frontier.push_back(std::make_pair(nx,ny));
			}
		}
		frontier.clear();
		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;
}