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 <string>
#include <set>
using namespace std;

const int MAX_H = 1005;
const int MAX_W = 1005;

string all[MAX_H];
int dx[4] = { 1, 0, -1, 0 };
int dy[4] = { 0, 1, 0, -1 };
int h, w;
int n;
int sx, sy;
typedef pair<int ,int> P;

int bfs(char target){
	set<P> s;
	queue<P> q1;
	queue<int> q2;
	q1.push(P(sy, sx));
	s.insert(P(sy, sx));
	q2.push(0);
	while (!q1.empty()){
		P p = q1.front(); q1.pop();
		int t = q2.front(); q2.pop();
		//cout << p.first << " " << p.second <<" "<<t<< endl;
		for (int i = 0; i < 4; ++i){
			int y = p.first + dy[i], x = p.second + dx[i];
			if (x >= 0 && x < w &&y >= 0 && y < h && all[y][x] != 'X'){
				if (s.count(P(y,x))){
					continue;
				}
				if (all[y][x] == target){
					all[y][x] = '.';
					sx = x, sy = y;
					return t + 1;
				}
				else{
					q1.push(P(y, x));
					q2.push(t + 1);
					s.insert(P(y, x));
				}
			}
		}
	}
}

void solve(){
	int ans = 0;
	char t = '1';
	for (int i = 0; i < n;++i){
		ans += bfs(t);
		++t;
	}
	cout << ans << endl;
}

int main(){
	cin >> h >> w >> n;
	for (int i = 0; i < h; ++i){
		cin >> all[i];
		for (int j = 0; j < w; ++j){
			if (all[i][j] == 'S'){
				sx = j, sy = i;
				all[i][j] = '.';
			}
		}
	}
	solve();
	return 0;
}

C++: #include <iostream>
#include <cstdio>
#include <queue>
#include <vector>
#include <map>
#include <stdlib.h>

#define rep(i, a, b) for(int i = (a); (i) < (b); (i)++)
#define ft first
#define sd second

using namespace std;

char m[1000][1000];
int dis[1000][1000];
queue<pair<int, int> > state;

int main() {
  int h, w, n;

  cin >> h >> w >> n;

  int sx, sy;
  rep(i, 0, h) {
    rep(j, 0, w) {
      cin >> m[j][i];
      if(m[j][i] == 'S') {
	sx = j;
	sy = i;
      }
    }
  }

  pair<int, int> p;
  p.ft = sx;
  p.sd = sy;

  rep(i, 0, h) {
    rep(j, 0, w) {
      dis[j][i] = -1;
    }
  }
  dis[sx][sy] = 0;
  state.push(p);

  int dx[4] = {-1,   0,  1, 0};
  int dy[4] = { 0,  -1,  0, 1};
  int map2[1000][1000];
  for(int lp = 1; lp <= n; lp ++) {
    rep(i, 0, h) {
      rep(j, 0, w) {
	map2[j][i] = 0;
      }
    }

    while(state.size()) {

      pair<int, int> now = state.front();
      state.pop();
      map2[now.ft][now.sd] = 1;
      if(m[now.ft][now.sd] - '0' == lp) {
	sx = now.ft;
	sy = now.sd;
	break;
      }
      
      rep(lp2, 0, 4) {
	int x = now.ft+dx[lp2];
	int y = now.sd+dy[lp2];
	
	if(x < 0 || w <= x || y < 0 || h <= y) continue;
	if(map2[x][y] == 0 && m[x][y] != 'X') {
	  state.push(make_pair(x, y));
	  dis[x][y] = dis[now.ft][now.sd] + 1;
	}
      }
    }
    while(state.size()) state.pop();

    state.push(make_pair(sx, sy));
  }

  cout << dis[sx][sy] << endl;
  return 0;
}

C++: //C++14 (Clang 3.8.0)

#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <string>
#define rp(i,a,b) for(int (i)=(int)(a);i<(int)(b);++i)
using namespace std;
typedef pair<int ,int> P;
int d[1001][1001],movex[]={0,0,-1,1},movey[]={1,-1,0,0};
char cc[]={'1','2','3','4','5','6','7','8','9'},a[1001][1001];
int h,w;
int nx,ny;
int bfs(int sx,int sy,char goal){
    queue<P> que;
    for(int i=0;i<h;i++){
        for(int j=0;j<w;j++){
            d[i][j]=-1;
        }
    }
    que.push(P(sx,sy));
    d[sx][sy]=0;
    int dis;
    while(que.size()){
        P p = que.front();que.pop();
        if(a[p.first][p.second]==goal) {nx=p.first;ny=p.second;return d[p.first][p.second];}
        for(int i = 0; i < 4; i++){
            int x=p.first+movex[i],y=p.second+movey[i];
            if(0<=x and x<h and 0<=y and y<w and d[x][y]==-1 and a[x][y]!='X'){
                que.push(P(x,y));
                d[x][y]=d[p.first][p.second]+1;
            }
        }
    }
    
}

int main(){
    int n;
    cin>>h>>w>>n;
    int x,y;
    for(int i=0;i<h;i++){
        for(int j=0;j<w;j++){
            cin>>a[i][j];
            if(a[i][j]=='S'){nx=i;ny=j;}
        }
    }
    for(int i=0;i<h;i++){
        for(int j=0;j<w;j++){
            cout<<a[i][j]<<" ";
        }
        cout<<endl;
    }

    int ans=0;
    for(int i=0;i<n;i++){
        ans+=bfs(nx,ny,cc[i]);
    }
    cout<<ans<<endl;

}

C++: #include <cstdio>
#include <cstdlib>
#include <queue>

char map[1000][1000];
int check[1000][1000];
int cx[10];
int cy[10];

int main(){
	int i,j,k,l,h,w,ch,pd=0;
	int tex,tey,ted;
	std::queue<int> qx;
	std::queue<int> qy;
	std::queue<int> qd;

	scanf("%d %d %d",&h,&w,&ch);
	scanf("%c",&map[0][0]);
	for(i=0;i<h;i++){
		for(j=0;j<=w;j++){
			scanf("%c",&map[i][j]);
			if(map[i][j]=='S'){cy[0]=i; cx[0]=j;}
			if(map[i][j]=='1'){cy[1]=i; cx[1]=j;}
			if(map[i][j]=='2'){cy[2]=i; cx[2]=j;}
			if(map[i][j]=='3'){cy[3]=i; cx[3]=j;}
			if(map[i][j]=='4'){cy[4]=i; cx[4]=j;}
			if(map[i][j]=='5'){cy[5]=i; cx[5]=j;}
			if(map[i][j]=='6'){cy[6]=i; cx[6]=j;}
			if(map[i][j]=='7'){cy[7]=i; cx[7]=j;}
			if(map[i][j]=='8'){cy[8]=i; cx[8]=j;}
			if(map[i][j]=='9'){cy[9]=i; cx[9]=j;}
		}
	}
	for(i=0;i<h;i++){
		for(j=0;j<=w;j++)check[i][j]=0;
	}

	i=0;
	while(i<ch){
		qx.push(cx[i]); qy.push(cy[i]); qd.push(0);
		++i;
		while(!qx.empty()){
			tex=qx.front(); tey=qy.front(); ted=qd.front();
			qx.pop(); qy.pop(); qd.pop();
			check[tey][tex]=1;
			if(tey==cy[i] && tex==cx[i]){
				pd+=ted;
				while(!qx.empty())qx.pop();
				while(!qy.empty())qy.pop();
				while(!qd.empty())qd.pop();
				for(k=0;k<h;k++){
					for(l=0;l<=w;l++)check[k][l]=0;
				}
				break;
			}
			++ted;
			if(tex+1<w && map[tey][tex+1]!='X' && check[tey][tex+1]==0){
				qx.push(tex+1); qy.push(tey); qd.push(ted);
			}
			if(tex-1>=0 && map[tey][tex-1]!='X' && check[tey][tex-1]==0){
				qx.push(tex-1); qy.push(tey); qd.push(ted);
			}
			if(tey+1<h && map[tey+1][tex]!='X' && check[tey+1][tex]==0){
				qx.push(tex); qy.push(tey+1); qd.push(ted);
			}
			if(tey-1>=0 && map[tey-1][tex]!='X' && check[tey-1][tex]==0){
				qx.push(tex); qy.push(tey-1); qd.push(ted);
			}
		}
	}

	printf("%d\n",pd);
	return 0;
}