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<algorithm>
#include<queue>
#define INF 10000000
using namespace std;
struct data{
    int x,y;
};
int H,W,N;
int ans[1001][1001];
char field[1001][1001];
int cou,sx,sy;
void bfs(data start,int num){
    int dx[]={0,1,0,-1},dy[]={1,0,-1,0};
    data g;
    for(int i=0;i<H;i++){
        for(int j=0;j<W;j++){
            ans[i][j]=INF;
            if(field[i][j]==num+'0'){
                g.x=i,g.y=j;
            }
        }
    }
    ans[start.x][start.y]=0;
    queue<data> q;
    q.push(start);
    while(!q.empty()){
        data now=q.front();
        q.pop();
        if(now.x==g.x&&now.y==g.y)break;
        int nex,ney;
        for(int i=0;i<4;i++){
            nex=now.x+dx[i];
            ney=now.y+dy[i];
            if(nex>=0&&nex<H&&ney>=0&&ney<W&&field[nex][ney]!='X'&&ans[nex][ney]==INF){
                data nowne;
                nowne.x=nex,nowne.y=ney;
                q.push(nowne);
                ans[nex][ney]=ans[now.x][now.y]+1;
            }
        }
    }
    cou+=ans[g.x][g.y];
    if(num!=N)bfs(g,num+1);
}
int main(){
    data s;
    cin>>H>>W>>N;
    for(int i=0;i<H;i++){
        for(int j=0;j<W;j++){
            cin>>field[i][j];
            if(field[i][j]=='S'){
                s.x=i,s.y=j;
            }
        }
    }
    bfs(s,1);
    cout<<cou<<endl;
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 = 100000;
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;
}

C++: #include <cstdio>
#include <queue>
using namespace std;

int H, M, N;
int go[4][2];
bool K[1002][1002];
bool flg[1002][1002];
int score[1002][1002];
int C[11][2];
int ans = 0;

struct Tops{
  int tx, ty, co;
  
  Tops(int x, int y, int c){
    tx = x;
    ty = y;
    co = c;
  }
};

queue<Tops> que;

int cal(int x, int y){
  while(!que.empty()){
    Tops t = que.front();
    que.pop();
    flg[t.tx][t.ty] = false;
    if(t.tx == x && t.ty == y){
      return t.co;
    }
    for(int i = 0; i < 4; i++){
      if(flg[t.tx + go[i][0]][t.ty + go[i][1]]){
        que.push(Tops(t.tx + go[i][0], t.ty + go[i][1], t.co + 1));
      }
    }
  }
  return 2147483647;
}

int main(){
  
  go[0][0] = 1;
  go[0][1] = 0;
  go[1][0] = 0;
  go[1][1] = -1;
  go[2][0] = -1;
  go[2][1] = 0;
  go[3][0] = 0;
  go[3][1] = 1;
  
  for(int i = 0; i <= H + 1; i++){
    for(int j = 0; j <= M + 1; j++){
      score[i][j] = 2147483640;
      flg[i][j] = false;
      K[i][j] = false;
    }
  }
  
  scanf("%d%d%d", &H, &M, &N);
  
  for(int i = 0; i < H; i++){
    char str[M + 1];
    scanf("%s", str);
    for(int j = 0; j < M; j++){
      if(str[j] == '.'){
        K[i + 1][j + 1] = true;
      }else if(str[j] == 'X'){
        K[i + 1][j + 1] = false;
      }else if(str[j] == 'S'){
        C[0][0] = i + 1;
        C[0][1] = j + 1;
        K[i + 1][j + 1] = true;
      }else{
        C[str[j] - '0'][0] = i + 1;
        C[str[j] - '0'][1] = j + 1;
        K[i + 1][j + 1] = true;
      }
    }
  }
  
  for(int i = 0; i < N; i++){
    for(int j = 0; j <= H + 1; j++){
      for(int k = 0; k <= M + 1; k++){
        flg[j][k] = K[j][k];
      }
    }
    while(!que.empty()){
      que.pop();
    }
    que.push(Tops(C[i + 1][0], C[i + 1][1], 0));
    int aa = cal(C[i][0], C[i][1]);
    ans += aa;
  }
  
  printf("%d\n", ans);
  
  return 0;
}