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 <utility>
#include <memory.h>

using namespace std;

#define INF 0x3f3f3f3f

int dist[1005][1005]; 
int goal[55];
char map[1005][1005];
int w, h, n;

typedef pair<int, int> P;
int dx[4] = {0, 1, 0, -1};
int dy[4] = {1, 0, -1, 0};
int ans;

int bfs(int x, int y)
{
    int sx = x;
    int sy = y;
    int res = 0;
    memset(goal, 0, sizeof(goal));
	for(int i = 1; i <= 10; ++i)
	{
		memset(dist, 0x3f, sizeof(dist));
	    dist[sy][sx] = 0;
        //map[sy][sx] = '.';
        queue<P> q;
        q.push(P(sx, sy));
        P tmp;
        while(!q.empty())
        {
            tmp = q.front();
            q.pop();
            if(map[tmp.second][tmp.first] == '0'+i)
            {
                goal[i] = dist[tmp.second][tmp.first];
                sy = tmp.second;
                sx = tmp.first;
        	    ans += dist[tmp.second][tmp.first];
		    }    
            for(int i = 0; i < 4; ++i)
            {
                int tx = tmp.first + dx[i];
                int ty = tmp.second + dy[i];
                if(tx >= 0 and tx < w and ty >= 0 and ty < h and map[ty][tx] != 'X' and dist[ty][tx] == INF)
                {    
			    	q.push(P(tx, ty));
			    	dist[ty][tx] = dist[tmp.second][tmp.first] + 1;
			    } 
            }
        }
        res += goal[i];
	}
    return res;
}

int main()
{
    cin>>h>>w>>n;
    int sx = 0, sy = 0;
    for(int i = 0; i < h; ++i)
        for(int j = 0; j < w; ++j)
        {
            cin>>map[i][j];
            if(map[i][j] == 'S')
            {
                sx = j;
                sy = i;
            }
        }
			
    cout<<bfs(sx, sy)<<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<W*H;step++)
	{
		std::cout << "step:" << step << std::endl;
		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++)
	{
		std::cout << "N\t" << i << std::endl;
		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 <bits/stdc++.h>
using namespace std ;

#define pb(n) push_back(n)
#define fi first
#define se second
#define X real()
#define Y imag()
#define value(x,y,w,h) (x >= 0 && x < w && y >= 0 && y < h)
#define all(r) (r).begin(),(r).end()
#define gsort(st,en) sort((st),(en),greater<int>())
#define vmax(ary) *max_element(all(ary))
#define vmin(ary) *min_element(all(ary))
#define debug(x) cout<<#x<<": "<<x<<endl
#define fcout(n) cout<<fixed<<setprecision((n))
#define scout(n) cout<<setw(n)
#define vary(type,name,size,init) vector< type> name(size,init)

#define rep(i,n) for(int i = 0; i < (int)(n);++i)
#define REP(i,a,b) for(int i = (a);i < (int)(b);++i)
#define repi(it,array) for(auto it = array.begin(),end = array.end(); it != end;++it)
#define repa(n,array) for(auto &n :(array))

using ll = long long;
using vi = vector<int>;
using vl = vector<ll>;
using dict = map<string,int>;
using comd = complex<double>;
using pii = pair<int,int> ;

constexpr int imax = ((1<<30)-1)*2+1 ;
constexpr int inf = 10000000;
constexpr double PI = acos(-1.0) ;
double eps = 1e-10 ;
const int dy[] = {-1,0,1,0};
const int dx[] = {0,-1,0,1};

int N,W,H,S;
vector<vector<int>> maps;
int main(){
  cin.tie(0);
  ios::sync_with_stdio(false);
  char c;
  int n = 0;
  cin >> W >> H >> N;
  char area[H][W];
  maps = vector<vector<int>>(H,vector<int>(W,inf));
  pii pos;
  rep(i,W){
    rep(j,H){
      cin >> c ;
      area[j][i] = c;
      if(c == 'S'){
        pos = make_pair(j,i);
        ++n;
      }
    }
  }
  queue<pii> q;
  q.push(pos);
  maps[pos.fi][pos.se] = 0;
  n = 1;
  int ans = 0;
  while(!q.empty()){
    pii p = q.front();q.pop();
    rep(i,4){
      int x = p.fi + dx[i],y = p.se+dy[i];
      if(value(x,y,H,W)){
        if(area[x][y] - '0' == n){
          ans += maps[p.fi][p.se] + 1;
          maps = vector<vector<int>>(H,vector<int>(W,inf));
          maps[x][y] = 0;
          q = queue<pii>();
          q.push(make_pair(x,y));
          if(n == N){
            q.pop();
          }
          ++n;
          break;
        }
        else if(area[x][y] != 'X' && maps[x][y] >= maps[p.fi][p.se]+1){
          q.push(make_pair(x,y));
          maps[x][y] = maps[p.fi][p.se] +1 ;
        }
      }
    }
  }
  cout << ans << endl;
  return 0;
}