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<iostream>
#include<queue>
#include<algorithm>
#include<cstring>
using namespace std;
char field[1000][1000];
struct date{
    int x,y,cnt,hp;
    int a;
    bool flg[1000][1000];
};
int main(){
	int h,w,n;
	cin >> h >> w >> n;
	date start;
	int ans = 0;
	for(int i = 0; i < h; i++){
	    cin >> field[i];
	    for(int j = 0; j < w; j++){
            if(field[i][j] == 'S'){
                start.a=0,start.x = j,start.y=i,start,start.cnt=0,start.hp=1,start.flg[i][j]=0;
            }
            if(field[i][j] >= '0' && field[i][j] <= '9'){
                ans++;
            }
	    }
	}
	queue<date> Q;
	Q.push(start);
	int dx[]={1,-1,0,0},dy[]={0,0,1,-1};
	while(!Q.empty()){
        date d = Q.front();
        Q.pop();
        if(ans == start.a){
            ans = start.cnt;
            break;
        }
        for(int i = 0; i < 4; i++){
            int px = d.x+dx[i],py = d.y+dy[i];
            if(px < 0 || py < 0 || w <= px || h <= py || field[py][px] == 'X')continue;
            if(field[py][px] >= '0' && field[py][px] <= '9'){
                if(field[py][px] <= d.hp && field[py][px] >= '0' && d.flg[py][px] == 0){
                    d.hp++;
                    d.flg[py][px] = 1;
                    d.a++;
                }
            }
            d.cnt++;
            Q.push(d);
        }
	}
	cout << ans << endl;
	return 0;
}

C++: #include <cstdio>
#include <set>

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

const int MAXSIZE = 1000;
char field[MAXSIZE + 1][MAXSIZE + 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[MAXN + 1][MAXN + 1];
	std::set<std::pair<int,int>> frontier;
	frontier.insert(std::pair<int,int>{sx,sy});
	for(int step=0;step<1<<10;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++)
			{
				int nx = p.first+STEP[i][0];
				int 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::pair<int,int>{nx,ny});
			}
		}
		frontier = next_frontier;
	}
	return -1;
}

int solve()
{
	int total_step = 0;
	for(int i=1;i<N;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 <stdio.h>
#include <deque>

using namespace std;

const int INF = 0x3f3f3f3f;
typedef pair<int, int> P;
int h, w, n;
int sx, sy;
int gx, gy;
char cmap[1000][1000];
int goalSum;
int goal[10];
int d[1000][1000];
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, -1, 0, 1};

int bfs() {
    int res = 0;
    deque<P> que;
    for (int ci = 0; ci < n; ci++) {  //要?行n次循?，?找n次?点，?次?数?入goal[i], 最后累加起来是res 
        for (int i = 0; i < h; i++) {
            for (int j = 0; j < w; j++) {
                d[i][j] = INF;
            }
        }
        
        que.push_back(P(sx, sy));
        d[sx][sy] = 0;
        
        while(que.size()) {            
            int x = que.front().first;
            int y = que.front().second;
                        
            if ((int)cmap[x][y] == 49 + ci) {
                goal[ci] = d[x][y];
                sx = x;
                sy = y;
                break;
            }
            
            for (int i = 0; i < 4; i++) {
                int nx = x + dx[i];
                int ny = y + dy[i];
                if (nx >=0 && nx < h && ny >= 0 && ny < w && cmap[nx][ny] != 'X' && d[nx][ny] == INF) {
                    que.push_back(P(nx, ny));
                    d[nx][ny] = d[x][y] + 1;
                }
            }    
            que.pop_front();        
        }
        que.clear(); 
        res += goal[ci];
    }
    return res;
}

int main() {
    cin >> h >> w >> n;
    for (int i = 0; i < h; i++) {
        for (int j = 0; j < w; j++) {
            cin >> cmap[i][j];
            if (cmap[i][j] == 'S') {
                sx = i;
                sy = j;
            }
        }
    }
    goalSum = bfs();
    cout << goalSum << endl;
    return 0;
}

C++: #include <iostream>
#include <vector>
#include <queue>
#include <sstream>
#include <cstring>
//#include <fstream>

using namespace std;

char M[1001][1001];
const int INF = 10e8;

typedef pair<int, int> P;

int bfs (P & sp, int n, int size, int len )
{
	// up, right, down, left order
	const int dir[][2] = { { -1, 0 }, { 0, 1 }, { 1, 0 }, { 0, -1 } };

	int res = 0;
	vector <vector <int> > path (size, vector <int> (len, INF ) );
	queue <P> Q;
	P curr = sp;
	Q.push (curr);

	path[curr.first][curr.second] = 0;	

	while (!Q.empty() ){
		curr = Q.front(); Q.pop();
		if (M[curr.first][curr.second] == n + '0' ){
			break;
		} // end if
		for (int k = 0; k < 4; ++k){
			int nrow = curr.first  + dir[k][0];
			int ncol = curr.second + dir[k][1];
			if (nrow < 0 || nrow >= size || ncol < 0 || ncol >= len ){
				continue;
			} // end if
			if (M[nrow][ncol] != 'X' && path[nrow][ncol] == INF ){
				Q.push (P(nrow, ncol) );
				path[nrow][ncol] = path[curr.first][curr.second] + 1;
			} // end if
		} // end for
	} // end while
	
	res = path[curr.first][curr.second];

	sp.first = curr.first;
	sp.second = curr.second;

	return res;
}

int main()
{
//	cut here before submit 
//	freopen ("testcase.cheese3", "r", stdin );
	string str = "";
	int h, w, n;

	while (getline (cin, str ) ){
		stringstream ssn(str);
		ssn >> h >> w >> n;
		memset (M, 0, sizeof (M ) );
		P sp;
		for (int i = 0; i < h; ++i){
			getline (cin, str );
			for (int j = 0; j < w; ++j){
				M[i][j] = str[j];
				if (M[i][j] == 'S' ){
					sp.first = i; sp.second = j;
				} // end if
			} // end for
		} // end for

		int res = 0;
		P cp = sp;
		for (int i = 1; i <= n; ++i){
			res += bfs ( cp, i, h, w );
		} // end for
		cout << res << endl;

	} // end loop
		
	return 0;
}