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>
#include <algorithm>

using namespace std;

typedef pair<int, int> P;

const int INF = 100000000;
const int MAX_H = 1000;
const int MAX_W = 1000;
const int MAX_N = 9;

//&#36755;入
int H, W, N;
char maze[MAX_H][MAX_W + 1];

int sx, sy;
int d[MAX_H][MAX_W];

const int dx[4] = {-1, 1, 0, 0};
const int dy[4] = {0, 0, -1, 1};

//求以(sx, sy)&#20026;起点到&#36798;目&#26631;c的最短路径&#38271;度
int bfs(char c){
	//初始化
	for(int i = 0; i < H; i ++){
		fill(d[i], d[i] + W, INF);
	}
	d[sx][sy] = 0;
	queue<P> que;
	que.push(P(sx, sy));
	//&#23485;度&#20248;先
	while(!que.empty()){
		P p = que.front();
		que.pop();
		//已找到
		if(maze[p.first][p.second] == c){
			//重置起点
			sx = p.first;
			sy = p.second;
			break;
		}

		for(int i = 0; i < 4; i ++){
			int nx = p.first + dx[i], ny = p.second + dy[i];
			//判断是否可移&#21160;以及是否已&#32463;&#35775;&#38382;&#36807;
			if(0 <= nx && nx < H && 0 <= ny && ny < W && maze[nx][ny] != 'X' && d[nx][ny] == INF){
				que.push(P(nx, ny));
				d[nx][ny] = d[p.first][p.second] + 1;
			}
		}
	}
//	printf("%d, %d\n", sx, sy);
	return d[sx][sy];
}

void solve(){
	//找起始点
	for(int i = 0; i < H; i ++){
		for(int j = 0; j < W; j ++){
			if(maze[i][j] == 'S'){
				sx = i;
				sy = j;
				break;
			}
		}
	}
	//&#23485;度&#20248;先搜索
	int ans = 0;
	for(int i = 1; i <= N; i ++){
		ans += bfs('0' + i);
	}
	printf("%d\n", ans);
}

int main(int argc, char const *argv[]){

	scanf("%d %d %d", &H, &W, &N);
	for(int i = 0; i < H; i ++){
		scanf("%s", maze[i]);
	}
	solve();

	return 0;
}

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][MAX_SIZE + 1]={};

	std::vector<std::pair<int,int>> frontier;
	frontier.push_back(std::pair<int,int>{sx,sy});
	int nx,ny;
	for(int step=0;step<W*H;step++)
	{
		for(auto p:frontier)
		{
			if(p.first==ex && p.second==ey)	return step;
			is_visit[p.first][p.second] = true;
		}
		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.push_back(std::make_pair(nx,ny));
			}
		}
//		std::cout << "step:" << step << "\t" << next_frontier.size() << std::endl;
		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++: #include <iostream>
#include <string.h>
#include <queue>
#define MAX_H 1000
#define MAX_W 1000
using namespace std;

typedef pair<int,int> P; // x,y(j,i)

int H,W,N;
char f[MAX_H][MAX_W];
int min_dist[10][10]; // distance from S,1,...,9 to S,1,...,9
P pos[10]; // position of S,1,..,9

int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};

bool isvalid(int x, int y) {
    return (0 <= x && x < W && 0 <= y && y < H);
}

void calcDist() {
    int visit_dist[MAX_H][MAX_W];
    memset(min_dist,0,sizeof(min_dist));
   for(int k=0;k<=N;k++) { // start pos
       queue< P > Q;
       Q.push(pos[k]);
        memset(visit_dist,0,sizeof(visit_dist));
        visit_dist[pos[k].second][pos[k].first] = 1;
       while(!Q.empty()) {
           P p = Q.front(); Q.pop();
           int dist = visit_dist[p.second][p.first];
           char ch = f[p.second][p.first];
           if(ch == 'X') continue;

           if(ch == 'S') {
              min_dist[k][0] = dist; 
           } else if('1' <= ch && ch <= '9') {
               min_dist[k][ch - '0'] = dist;
           }

           for(int i=0;i<4;i++) {
               int x = p.first + dx[i];
               int y = p.second + dy[i];
               if (isvalid(x,y) && !visit_dist[y][x]) {
                   visit_dist[y][x] = dist + 1;
                   Q.push(make_pair(x,y));
               }
           }
       }
   } 
}

void solve() {
    calcDist();

    int ans = 0;
    for(int i=1;i<=N;i++) {
        ans += min_dist[i-1][i];
    }
    ans -= N;
    if(ans < 0) ans = 0;
    cout << ans << endl;
}

main() {
    cin>>H>>W>>N;
    for(int i=0;i<H;i++) {
        for(int j=0;j<W;j++) {
            cin>>f[i][j];
            if(f[i][j] == 'S') {
                pos[0] = make_pair(j,i);
            } else if('1' <= f[i][j] && f[i][j] <= '9') {
                pos[f[i][j] - '0'] = make_pair(j,i);
            }
        }
    }
    solve();
}