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

using namespace std;
typedef long long int ll;
typedef vector<int> VI;
typedef pair<int, int> PII;
typedef pair<int, pair<int,int>> tup;
#define ALL(a) (a).begin(), (a).end()
#define RALL(a) (a).rbegin(), (a).rend()

#define EACH(i, c) \
  for (typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define SORT(c) sort((c).begin(), (c).end())

#define FOR(i, a, b) for (int i = (a); i < (b); ++i)
#define REP(i, n) FOR(i, 0, n)
const double PI = acos(-1.0);
#define CLR(a) memset((a), 0, sizeof(a))

// int tansaku[110];
// map<string,string> d;
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};

int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);
  bool  visited[1010][1010];
  char field[1010][1010];
  queue<tup> kuwa;
  int H, W, N;
  //CLR(visited);
  REP(i,W){REP(j,H) visited[i][j]=false;}
  cin >> H >> W >> N;
  REP(j, H) {
    REP(i, W) { cin >> field[i][j]; }
  }
  tup start;
  cin.ignore();
  REP(i, W) {
    REP(j, H) {
      if (field[i][j] == 'S') {
        start = {0,{i, j}};
      }
    }
  }
  kuwa.push(start);
  int ans=0;
  int cost =0;
  char cheeze='1';
  while(!kuwa.empty()){
  	tup r = kuwa.front();kuwa.pop();
  	int haba = r.first;
  	PII p = r.second;
  	visited[p.first][p.second] = true;
  	if(field[p.first][p.second]==cheeze){
      cost += haba;
  		if(cheeze-'0' == N)break;
  		cheeze++;
  		queue<tup> daisuke;
  		swap(kuwa,daisuke);
  		kuwa.push(make_pair(0,p));
      //CLR(visited);
      REP(i,W){REP(j,H) visited[i][j]=false;}

  		continue;
  	}
  	for(int i=0 ; i<4 ;i++){
          PII new_xy = {p.first + dx[i], p.second + dy[i]};
          if(0 <= new_xy.first && new_xy.first < W &&
              0 <= new_xy.second && new_xy.second < H &&
                  !visited[new_xy.first][new_xy.second] &&
                  field[new_xy.first][new_xy.second] != 'X'){
          kuwa.push(make_pair(haba+1,new_xy));	
          }
        }
  }
  cout << cost << endl;
  return 0;
}

C++: #include <iostream>
#include <queue>
#define N 1002
#define INFINITY 2000000000
using namespace std;
int bfs(char,char);
int h,w,n,num[N][N];
int d[N*N],u,ret;
string str[N];
string color[N*N];
int main(){
  int i,j,number,ans;
  cin >> h >> w >> n;
  for(i=0;i<=w+1;i++) str[0]+='X',str[h+1]+='X';
  for(i=1;i<=h;i++){
    cin >> str[i];
    str[i]='X'+str[i]+'X';
  }
  number=1;
  for(i=0;i<=h+1;i++){
    for(j=0;j<=w+1;j++){
      if(str[i][j]=='X') num[i][j]=-1;
      else{
	num[i][j]=number;
	number++;
      }
    }
  }
  ans=bfs('S','1');
  for(i=1;i<n;i++){
    ans+=bfs(i+'0',i+1+'0');
  }
  cout << ans << endl;
  return 0;
}
int bfs(char s,char g){
  queue<int> q;
  int i,j;
  for(i=1;i<=h;i++){
    for(j=1;j<=w;j++){
      if(num[i][j]!=-1){
	color[num[i][j]]="WHITE";
	d[num[i][j]]=INFINITY;
      }
    }
  }
  for(i=1;i<=h;i++){
    for(j=1;j<=w;j++){
      if(str[i][j]==s){
	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(num[i][j]!=-1){
	  if((num[i-1][j]==u||num[i+1][j]==u||num[i][j+1]==u||num[i][j-1]==u)&&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(str[i][j]==g){
	ret=d[num[i][j]];
      }
    }
  }
  return ret;
}

C++: #include <iostream>
#include <cstdio>
#include <stack>
#include <queue>

using namespace std;
const int maxn = 1005;
const int inf = 1e6;

typedef pair<int, int> P;
char data[maxn][maxn];
int dist[maxn][maxn];
int sx, sy, w, h, n, sum;
P fac[15];

void initialize()
{
    for(int i=0; i<h; ++i)
    {
        for(int j=0; j<w; ++j)
        {
            dist[i][j] = inf;
        }
    }
}

void bfs(P s, P g)
{
    int a[4] = {-1, 0, 1, 0}, b[4] = {0, -1, 0, 1};
    queue<P> que;
    que.push(s);

    while(!que.empty())
    {
        P cur = que.front();
        que.pop();

        if(cur==g)  return;

        int x = cur.first, y = cur.second;
        for(int i=0; i<4; ++i)
        {
            int nx = x + a[i], ny = y + b[i];
            if(nx>=0 && nx<h && ny>=0 && ny<w && data[nx][ny]!='X' && dist[nx][ny]==inf)
            {
                que.push(P(nx, ny));
                dist[nx][ny] = min(dist[nx][ny], dist[x][y]+1);
            }
        }
    }
}

int main()
{
    //while(scanf("%d%d", &w, &h)!= EOF && w && h){
    scanf("%d%d%d", &h, &w, &n);
    for(int i=0; i<h; ++i)
        scanf("%s", &data[i]);

    for(int i=0; i<h; ++i)
    {
        for(int j=0; j<w; ++j)
        {
            if(data[i][j]=='S')
            {
                fac[0] = P(i,j);
            }
            else if(data[i][j]>='1' && data[i][j]<='9')
                fac[data[i][j]-'0'] = P(i,j);
        }
    }
    sum = 0;
    for(int i=1; i<=n; ++i)
    {
        int x = fac[i-1].first, y = fac[i-1].second;
        initialize();
        dist[x][y] = 0;
        bfs(fac[i-1], fac[i]);
        //data[x][y] = '.';
        sum += dist[fac[i].first][fac[i].second];
        //cout << sum << endl;
    }
    printf("%d\n", sum);

    //}
    return 0;
}