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>
#define N 1002
#define INFINITY 2000000000
using namespace std;
void bfs();
int h,w,n,num[N][N],d[N],M[N][N],u,m;
string color[N],in[N];
int main(){
  int i,j,k;
  cin >> h >> w >> n;
  for(i=0;i<h+2;i++)
    for(j=0;j<w+2;j++)
      num[i][j]=-1;
  for(i=1;i<=h;i++) cin >> in[i],in[i]='X'+in[i];
  k=0;
  for(i=1;i<=h;i++){
    for(j=1;j<=w;j++){
      if(in[i][j]!='X') num[i][j]=k,k++;
    }
  }
  m=max(h,w);
  for(i=0;i<=m;i++)
    for(j=0;j<=m;j++)
      M[i][j]=0;
  for(i=1;i<=h;i++){
    for(j=1;j<=w;j++){
      if(num[i][j]!=-1&&num[i+1][j]!=-1)
	M[num[i][j]][num[i+1][j]]=M[num[i+1][j]][num[i][j]]=1;
      if(num[i][j]!=-1&&num[i][j+1]!=-1)
	M[num[i][j]][num[i][j+1]]=M[num[i][j+1]][num[i][j]]=1;
    }
  }
  bfs();
  return 0;
}
void bfs(){
  int i,j,p=1,t=0,flag=0,x=1;
  char start='S',goal='1';
  queue<int> q;
  while(1){
    if(flag==1) start=x+'0',goal=x+'0'+1,x++;
    for(i=1;i<=h;i++){
      for(j=1;j<=w;j++){
	color[num[i][j]]="WHITE",d[num[i][j]]=INFINITY;
      }
    }
    for(i=1;i<=h;i++){
      for(j=1;j<=w;j++){
	if(in[i][j]==start) color[num[i][j]]="GLAY",d[num[i][j]]=0,q.push(num[i][j]);
      }
    }
    while(q.empty()!=1){
      u=q.front();
      q.pop();
      for(i=1;i<=h;i++){
	for(j=1;j<=w;j++){
	  if(M[u][num[i][j]]&&color[num[i][j]]=="WHITE"){
	    color[num[i][j]]="GLAY";
	    d[num[i][j]]=d[u]+1;
	    q.push(num[i][j]);
	  }
	}
      }
      color[u]="BLACK";
    }
    for(i=1;i<=h;i++){
      for(j=1;j<=w;j++){
	if(in[i][j]==goal) t+=d[num[i][j]];
      }
    }
    flag=1;
    if(x>n) break;
  }
  cout << t << endl;
}

C++: #include<iostream>
#include<vector>
#include<map>
#include<utility>
#include<queue>
using namespace std;
 
char f[1001][1001];
int d[1001][1001];
int h , w , n , x , y , ans;
typedef pair<int,int> P;
int dx[] = {1,0,-1,0} , dy[] = {0,-1,0,1};
 
int bfs(int to){
  for( int i = 0 ; i < h ; i++)
    for( int j = 0 ; j < w ; j++)
      d[i][j] = 0;
  queue<P> q;
  q.push(make_pair(x,y));
  d[x][y]=1;
  while(!q.empty()){
    P p = q.front();
    q.pop();
    if(f[p.second][p.first] - '0' == to){
      x = p.first;
      y = p.second;
      break;
    }
    for(int i = 0 ; i < 4 ; i ++){
      int nx = p.first + dx[i], ny = p.second + dy[i];
      if(nx >= 0 && nx < w && ny < h && ny >=0 && d[ny][nx] == 0 && f[ny][nx] != 'X'){
        d[ny][nx] = d[p.second][p.first] + 1;
        q.push(make_pair(nx,ny));
        
      }
    }
  }
  return d[y][x] - 1;
} 
 
int main(){
  while(cin >> h >> w >> n){
    for( int i = 0 ; i < h ; i++) cin >> f[i];
    for( int i = 0 ; i < h ; i++){ 
      for( int j = 0 ; i < w ; i++){
	if(f[j][i]=='S'){
	  x = j;
	  y = i;
	}
      }
    }
    for( int i = 0 ; i < n ; i++ ) ans +=bfs(i) ; 
    cout << ans << endl;
  }
}

C++: #include<iostream>
#include<algorithm>
#include<queue>
#include<cstdio>
#define INF 99999999
using namespace std;
typedef pair <int,int> P;
int sx,sy; 
int H,W,N;
int ans=0,g=0;
char S[1010][1010];
int gx,gy;
int d[1010][1010];
int dx[4] = {0,1,0,-1},dy[4] = {1,0,-1,0};
int bfs();
int main(){
  cin >> H >> W >> N;
  for(int i=0;i<H;i++){
    for(int j=0;j<W;j++){
      cin >> S[i][j];
      if(S[i][j] == 'S'){
	sx = i;
	sy = j;
      }
    }
  }
  for(int i=0;i<N;i++){
    int res = bfs();
    ans += res;
    g++;
  }
  cout << ans <<  endl;
}
int bfs(){
  queue <P> qu;
  for(int i=0;i<H;i++){
    for(int j=0;j<W;j++){
      d[i][j] = INF;
      if(S[i][j] == '1' + g){
	gx = i;
	gy = j;
      }
    }
  }
  qu.push(P(sx,sy));
  d[sx][sy] = 0;
  while(!qu.empty()){
    P p = qu.front();
    qu.pop();
    if(p.first == gx && p.second == gy)break;
    for(int i=0;i<4;i++){
      int nx = p.first + dx[i];
      int ny = p.second + dy[i];
      if(0 <= nx && nx < H && 0 <= ny && ny < W && S[nx][ny] != 'X' && d[nx][ny] == INF){
	qu.push(P(nx,ny));
	d[nx][ny] = d[p.first][p.second] + 1;
      }
    }
  }
  sx = gx;
  sy = gy;
  return d[gx][gy];
}

C++: #include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <map>
#include <sstream>
#include <functional>
#include <numeric>
#include <cmath>
#include <cstring>
#include <cstdio>
#include <queue>
#include <stack>
#include <set>

using namespace std;

#define ALL(co) co.begin(), co.end()
#define tpl(...) make_tuple(__VA_ARGS__)

typedef long long LL;
typedef pair<int, int> P; typedef pair<int, P> IP; typedef pair<P, P> PP;
typedef vector<int> Array; typedef vector<vector<int> > Array2;
typedef vector<LL> LArray; typedef vector<P> PArray; typedef vector<string> SArray;

const int INF = 1 << 29;
const LL LINF = 1LL << 60;

inline int getInt() { int itiv; return (cin >> itiv, itiv); }
template <typename T> void readAll(vector<T>& vec) { for (int i = 0, size = vec.size(); i < size; i++) cin >> vec[i]; }
template <typename T, typename U> void readAll(vector<pair<T, U> >& vec) { for (int i = 0, size = vec.size(); i < size; i++) cin >> vec[i].first >> vec[i].second; }
template < typename T > inline string toString( const T &a ){ ostringstream oss; oss << a; return oss.str(); };
inline bool between(int min, int max, int n) { return min <= n && n <= max; }
inline bool inRange(int begin, int end, int n) { return begin <= n && n < end; }
inline bool inRange(int size, int n) { return 0 <= n && n < size; }

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


int main(void)
{
	ios::sync_with_stdio(false);
	int h, w, n;
	while(cin >> h >> w >> n && n)
	{
		SArray stage(h);
		PArray cheese(n + 1);
		for (int i = 0; i < h; i++)
		{
			cin >> stage[i];
			for (int j = 0; j < w; j++)
			{
				char c = stage[i][j];
				if(c == 'S')
				{
					cheese[0] = P(i, j);
				}
				if(inRange(10, c - '0'))
				{
					cheese[c - '0'] = P(i, j);
				}
			}
		}

		int ans = 0;
		for (int i = 0; i < n; i++)
		{
			P start = cheese[i];
			P goal = cheese[i + 1];

			vector<vector<bool>> visited(h, vector<bool>(w));
			queue<IP> que;
			que.push(IP(0, start));
			while (!que.empty())
			{
				IP ip = que.front(); que.pop();
				P p = ip.second;
				visited[p.first][p.second] = true;

				if(p == goal)
				{
					ans += ip.first;
					break;
				}

				for (int j = 0; j < 4; j++)
				{
					int nr = p.first + dr[j], nc = p.second + dc[j];
					if(!inRange(h, nr) || !inRange(w, nc) || stage[nr][nc] == 'X' || visited[nr][nc]) continue;
					visited[p.first][p.second] = true;
					que.push(IP(ip.first + 1, P(nr, nc)));
				}
			}
		}

		cout << ans << endl;
	}
	return 0;
}