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
#include<bits/stdc++.h>

//using
using namespace std;


//define static const typedef
#define FOR(i, s, n) for(int i = s; i < int(n); i++)
#define REP(i, n) FOR((i), 0, (n))
#define ALL(a) (a).begin(), (a).end()
#define RALL(a) (a).rbegin(), (a).rend()
#define PB push_back
#define MP make_pair
#define SORT(a) sort(ALL(a))
#define RSORT(a) sort(RALL(a))
#define DUMP(x) cerr << #x << " = " << x << "\n";
#define DEBUG(x) cerr << #x << " = " << x << " (L:" << __LINE__ << ") " << __FILE__ << "\n";
#define F first
#define S second

typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<string> VS;
typedef pair<int, int> PII;
typedef vector<PII> VPII;
typedef long long LL;
typedef vector<LL> VLL;
typedef vector<VLL> VVLL;
typedef unsigned long long ULL;

static const int INF = 1 << 25;
static const int movex[] = {0,0,1,-1};
static const int movey[] = {1,-1,0,0};
//global
static int a, b, c, ans, hp = 1;
static VS mp;
static int sx = INF, sy = INF;
static string str = "";
static char inp[1000];
static vector<VVI> ar;
static queue<pair<int, PII > >  n;
//function
int main(){
  scanf("%d %d %d", &a, &b, &c);
  REP(i, b + 2){
    str = str + "X";
  }
  mp.PB(str);
  REP(i, a){
    scanf("%s", inp);
    mp.PB(inp);
    mp[i + 1] = "X" + mp[i + 1] + "X";
    REP(j, mp[i + 1].size()){
      if(sx != INF){
	break;
      }
      if(mp[i + 1][j] == 'S'){
	sy = i + 1;
	sx = j;
	break;
      }
    }
  }
  ar.resize(c, VVI(a + 2, VI(b + 2)));
  REP(i, c){
    REP(j, a + 2){
      REP(k, b + 2){
	ar[i][j][k] = INF;
	if(!i && sy == j && sx == k){
	  ar[0][j][k] = 0;
	}
      }
    }
  }
  mp.PB(str);
  n.push(pair<int, PII>(hp, PII(sy, sx)));

  while(!n.empty()){
    if(n.front().F != hp){
      n.pop();
      continue;
    }
    if(hp == mp[n.front().S.F][n.front().S.S] - '0'){
      hp++;
      if(hp > c){
	ans = ar[c - 1][n.front().S.F][n.front().S.S];
	break;
      }
      ar[hp - 1][n.front().S.F][n.front().S.S] = ar[hp - 2][n.front().S.F][n.front().S.S];
    }
    int nowy = n.front().S.F, nowx = n.front().S.S;
    n.pop();
    REP(i, 4){
      if(mp[nowy + movey[i]][nowx + movex[i]] != 'X' && ar[hp - 1][nowy + movey[i]][nowx + movex[i]] > ar[hp - 1][nowy][nowx] + 1){
	ar[hp - 1][nowy + movey[i]][nowx + movex[i]] = ar[hp - 1][nowy][nowx] + 1;
	n.push(pair<int, PII>(hp, PII(nowy + movey[i], nowx + movex[i])));
      }
    }
  }
  printf("%d\n",ans);
  return 0;
}

C++: #include <cstdio>
#include <cstring>
#include <queue>
#include <utility>
using namespace std;
typedef pair<int,int> _P;
typedef pair<_P,int> P;
char map[1000][1001];
bool vst[1000][1000];
int dx[]={1,0,-1,0},dy[]={0,1,0,-1};
int H,W,N,x,y;
int bfs(char ch) {
	memset(vst,0,sizeof(vst));
	queue<P> Q;
	Q.push(P(_P(x,y),0));
	vst[x][y]=true;
	while(!Q.empty()) {
		P p=Q.front(); Q.pop();
		if(map[p.first.second][p.first.first]==ch) {x=p.first.first; y=p.first.second;return p.second;}
		for(int i=0;i<4;i++) {
			int nx=p.first.first+dx[i],ny=p.first.second+dy[i];
			if(0>nx||nx>=W||0>ny||ny>=H) continue;
			if(vst[nx][ny]) continue;
			if(map[ny][nx]=='X') continue;
			Q.push(P(_P(nx,ny),p.second+1));
			vst[nx][ny]=true;
		}
	}
}
int main() {
	scanf("%d %d %d",&H,&W,&N);
	for(int i=0;i<H;i++) {
		scanf("%s",map[i]);
		for(int j=0;j<W;j++)
			if(map[i][j]=='S') x=j,y=i;
	}
	int sum=0;
	for(int i=1;i<=N;i++)
		sum+=bfs(i+'0');
	printf("%d\n",sum);
}

C++: #include<iostream>
#include<queue>
using namespace std;
#define REP(i,n) for(int i=0;i<(n);i++)
#define PII pair<int,int>
#define MP make_pair

int ctoi(char c)
{
	if ('0' <= c&&c <= '9')return (c - '0');
	else return -1;
}

char MAP[1000][1000];
char tMAP[1000][1000];
PII D[9];
int dx[4] = { 1,0,-1,0 };
int dy[4] = { 0,1,0,-1 };

int main()
{
	int H, W, N;
	PII S;
	cin >> H >> W >> N;
	REP(i, H)REP(j, W)
	{
		char temp;
		cin >> temp;
		if (temp == 'S')
		{
			MAP[i][j] = '.';
			S = MP(j, i);
		}
		else if (temp == '.' || temp == 'X')MAP[i][j] = temp;
		else
		{
			int t = ctoi(temp);
			MAP[i][j] = '.';
			D[t - 1] = MP(j, i);
		}
	}
	int sum = 0;
	int index = 0;
	while (1)
	{
		REP(i, H)REP(j, W)tMAP[i][j] = MAP[i][j];
		if (S == D[N - 1])break;
		int timer = 0;
		queue <PII> q;
		queue <int> t;
		q.push(S);
		t.push(timer);
		while (1)
		{
			if (t.front() > timer)timer++;
			if (q.front() == D[index])
			{
				sum += timer;
				S = D[index];
				index++;
				break;
			}
			for (int i = 0; i < 4; i++)
			{
				int tx = q.front().first + dx[i];
				int ty = q.front().second + dy[i];
				if (0 <= tx&&tx <= W - 1 && 0 <= ty&&ty <= H - 1)
				{
					if (tMAP[ty][tx] == '.')
					{
						tMAP[ty][tx] = 'X';
						q.push(MP(tx, ty));
						t.push(timer + 1);
					}
				}
			}
			q.pop();
			t.pop();
		}
	}
	cout << sum << endl;
	return 0;
}