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<stdio.h>
#include<string.h>

#include<iostream>
#include<queue>


using namespace std ;


#define y .first
#define x .second


pair< int ,int > p ,cpy ;


char route[ 1000 ][ 1000 + 1 ] ;

int came[ 1000 ][ 1000 ] ;


bool check( pair< int ,int > now,int h,int w ) ;

#define size sizeof came


int mx[] = { 1 ,0 ,0 ,-1 } ;
int my[] = { 0 ,1 ,-1 ,0 } ;


int main()
{
	int h ,w ,n ;
	scanf( "%d %d %d" ,&h ,&w ,&n ) ;

	char end = '0' + n ,cheese = '1' ;

	scanf( "%c" ,&route[ 0 ][ 0 ] ) ;

	int i ,j ;
	for( i = 0 ; i < h ; ++i )
	{
		for( j = 0 ; j <= w ; ++j )
		{
			scanf( "%c" ,&route[ i ][ j ] ) ;

			if( route[ i ][ j ] == 'S' )
			{
				p y = i ;
				p x = j ;
			}
		}
	}

	int ans = 0 ;
	
	do
	{
		queue< pair< int ,int > > que ;

		memset( came ,0 ,size ) ;

		while( route[ p y ][ p x ] != cheese )
		{
			int i ;
			for( i = 0 ; i < 4 ; ++i )
			{
				cpy y = p y + my[ i ] ;
				cpy x = p x + mx[ i ] ;

				if( route[ cpy y ][ cpy x ] != 'X' && check( cpy ,h ,w ) == true )
				{
					came[ cpy y ][ cpy x ] = came[ p y ][ p x ] + 1 ;

					que.push( cpy ) ;
				}
			}

			came[ p y ][ p x ] = 1 ;

			p = que.front() ;

			que.pop() ;
		}

		++cheese ;

		ans += came[ p y ][ p x ] ;

	}while( cheese <= end ) ;

	printf( "%d\n" ,ans ) ;


	return 0 ;
}


bool check( pair< int ,int > now ,int h ,int w )
{
	if( now y >= h || now x >= w || now y < 0 || now x < 0 )
		return false ;

	else if( came[ now y ][ now x ] > 0 )
		return false ;

	return true ;
}

C++: #include<algorithm>
#include<functional>
#include<cmath>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<string>
#include<sstream>
#include<iostream>
#include<iomanip>
#include<vector>
#include<list>
#include<stack>
#include<queue>
#include<map>
#include<set>
#include<bitset>
#include<climits>
 
#define all(c) (c).begin(), (c).end()
#define rep(i,n) for(int i=0;i<(n);i++)
#define pb(e) push_back(e)
#define mp(a, b) make_pair(a, b)
#define fr first
#define sc second
 
typedef unsigned long long UInt64;
typedef long long Int64;
 
const int INF=100000000;
int dx[4]={1,0,-1,0};
int dy[4]={0,1,0,-1};
 
using namespace std;

typedef pair<int,int> P;

int h,w,n;
string maze[1000];

	int dist[1000][1000];
int bfs(char s,char t)
{
	int sx,sy,tx,ty;
	rep(i,1000) rep(j,1000) dist[i][j]=INF;

	rep(i,h) rep(j,w) 
	{
		if(maze[i][j]==s)
		{
			sx=i;
			sy=j;
		}
		if(maze[i][j]==t)
		{
			tx=i;
			ty=j;
		}

	}

	dist[sx][sy]=0;
	queue<P> que;
	que.push(P(sx,sy));

	while(que.size())
	{
		P p = que.front();
		que.pop();
		if(p.fr==tx&&p.sc==ty)
			return dist[tx][ty];

		rep(i,4)
		{
			int nx=p.fr+dx[i];
			int ny=p.sc+dy[i];
			if(0<=nx&&nx<h&&0<=ny&&ny<w&&maze[nx][ny]!='X'&&dist[nx][ny]==INF)
			{
				que.push(P(nx,ny));
				dist[nx][ny] = dist[p.fr][p.sc]+1;
			}
		}
	}

	return -INF;
}

int main()
{
	cin>>h>>w>>n;

	rep(i,h) cin>>maze[i];

	rep(i,h) rep(j,w) if(maze[i][j]=='S') maze[i][j]='0';
	int ans=0;
	rep(i,n)
		ans+=bfs(i+'0',i+1+'0');

	cout<<ans<<endl;



		return 0;
}

C++: #include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <utility>
#include <cctype>
#include <numeric>
using namespace std;

#define rep(i,n) for(int (i)=0; (i)<(int)(n); ++(i))
#define foreach(c,i) for(__typeof((c).begin()) i=(c).begin();i!=(c).end();i++)
struct State { int i, j, cost; };

int H, W, N;
vector<string> vs;
const int di[] = { 0, -1, 0, 1 };
const int dj[] = { 1, 0, -1, 0 };

void main2() {
  queue<State> Q;
  rep(i,H) rep(j,W) {
    if (vs[i][j] == 'S') Q.push((State){i,j,0});
  }
  int ans = 0;
  rep(loop,N) {
    vector<vector<int > > d(H, vector<int>(W, 1<<30));
    while (!Q.empty()) {
      State s = Q.front(); Q.pop();
      if (d[s.i][s.j] <= s.cost) continue;
      d[s.i][s.j] = s.cost;
      rep(i,4) {
        int ti = s.i + di[i], tj = s.j + dj[i];
        if (ti < 0 || tj < 0) continue;
        if (ti >= H || tj >= W || vs[ti][tj] == 'X') continue;
        if (d[ti][tj] > s.cost + 1)
          Q.push((State){ti, tj, s.cost + 1});
      }
    }
    rep(i,H) rep(j,W) if (vs[i][j] - '0' == loop+1) {
      ans += d[i][j];
      Q.push((State){i,j,0});
    }
  }
  printf("%d\n", ans);
}

int main() {
  while (cin >> H >> W >> N) {
    vs.clear();
    cin.ignore();
    string line;
    rep(i,H) {
      getline(cin, line);
      vs.push_back(line);
    }
    main2();
  }
  return 0;
}

C++: #include<queue>
#include<iostream>
#include<string>
#include<cstdlib>
#include<cstring>
#include<cmath>
using namespace std;
int main(){
  int i,j;
  int a[1002][1002],c[10],d[10],n,w,h,x,y,z;
  int sm=0;
  char s;
  bool b[1002][1002];
  queue<pair<pair<int,int>,int> > q;
  memset(a,-1,sizeof(a));
  cin>>h>>w>>n;
  for(i=1;i<h+1;i++){
    for(j=1;j<w+1;j++){
      cin>>s;
      if(s!='X'){
	a[j][i]=0;
	if(0){
	}else if(s=='.'){
	}else if(s=='S'){
	  c[0]=j;
	  d[0]=i;
	}else{
	  c[s-'0']=j;
	  d[s-'0']=i;
	}
      }
    }
  }
  for(i=0;i<n;i++){
    memset(b,0,sizeof(b));
    while(q.empty()==0)
      q.pop();
    q.push(make_pair(make_pair(c[i],d[i]),0));
    for(;;){
      x=q.front().first.first;
      y=q.front().first.second;
      z=q.front().second;
      q.pop();
      if(a[x][y]!=-1&&b[x][y]==0){
	if(x==c[i+1]&&y==d[i+1])
	  break;
	b[x][y]=1;
	q.push(make_pair(make_pair(x-1,y),z+1));
	q.push(make_pair(make_pair(x,y-1),z+1));
	q.push(make_pair(make_pair(x+1,y),z+1));
	q.push(make_pair(make_pair(x,y+1),z+1));
      }
    }
    sm+=z;
  }
  cout<<sm<<endl;
  return 0;
}