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 ;

#define pb(n) push_back(n)
#define fi first
#define se second
#define X real()
#define Y imag()
#define value(x,y,w,h) (x >= 0 && x < w && y >= 0 && y < h)
#define all(r) (r).begin(),(r).end()
#define gsort(st,en) sort((st),(en),greater<int>())
#define vmax(ary) *max_element(all(ary))
#define vmin(ary) *min_element(all(ary))
#define debug(x) cout<<#x<<": "<<x<<endl
#define fcout(n) cout<<fixed<<setprecision((n))
#define scout(n) cout<<setw(n)
#define vary(type,name,size,init) vector< type> name(size,init)

#define rep(i,n) for(int i = 0; i < (int)(n);++i)
#define REP(i,a,b) for(int i = (a);i < (int)(b);++i)
#define repi(it,array) for(auto it = array.begin(),end = array.end(); it != end;++it)
#define repa(n,array) for(auto &n :(array))

using ll = long long;
using vi = vector<int>;
using vl = vector<ll>;
using dict = map<string,int>;
using comd = complex<double>;
using pii = pair<int,int> ;

constexpr int imax = ((1<<30)-1)*2+1 ;
constexpr int inf = 1000;
constexpr double PI = acos(-1.0) ;
double eps = 1e-10 ;
const int dy[] = {-1,0,1,0};
const int dx[] = {0,-1,0,1};

int N,W,H,S;

int main(){
  cin.tie(0);
  ios::sync_with_stdio(false);
  char c;
  int n = 0;
  cin >> W >> H >> N;
  vector<vector<char>> area(H,vector<char>(W,0));
  vector<vector<int>> maps(H,vector<int>(W,inf)),save;
  vector<pii> pos(N+1);
  rep(i,W){
    rep(j,H){
      cin >> c ;
      area[j][i] = c;
      if(c == 'S'){
        pos[n] = make_pair(j,i);
        ++n;
      }
      else if(c - '0' == n){
        pos[n] = make_pair(j,i);
        ++n;
      }
    }
  }
  save = maps;
  queue<pii> q;
  q.push(pos[0]);
  maps[pos[0].fi][pos[0].se] = 0;
  n = 1;
  int ans = 0;
  while(!q.empty()){
    pii p = q.front();q.pop();
    rep(i,4){
      int x = p.fi + dx[i],y = p.se+dy[i];
      if(value(x,y,H,W)){
        if(area[x][y] - '0' == n){
          ans += maps[p.fi][p.se] + 1;
          maps = save;
          maps[x][y] = 0;
          q = queue<pii>();
          q.push(make_pair(x,y));
          if(n == N){
            q.pop();
          }
          ++n;
          break;
        }
        else if(area[x][y] != 'X' && maps[x][y] >= maps[p.fi][p.se]+1){
          q.push(make_pair(x,y));
          maps[x][y] = maps[p.fi][p.se] +1 ;
        }
      }
    }
  }
  cout << ans << endl;
  return 0;
}

C++: #include<iostream>
#include<queue>
#include<vector>
using namespace  std;
int h, w, n;
int sy = 0, sx = 0;
int dy[] = {0,0,1,-1};
int dx[] = {1,-1,0,0};
char field[1000 + 1][1000 + 1];
int main()
{
	cin >> h >> w >> n;
	for (int i = 0; i < h; i++)
	{
		cin >> field[i];
		for (int j = 0; j < w; j++)
		{
			if (field[i][j] == 'S')
			{
				sy = i;
				sx = j;
			}
		}
	}
	int ans = 0;
	for (int m = 1; m <= n; m++)
	{
		bool used[1000 + 1][1000 + 1];
		queue<pair<pair<int, int>, int> > q;
		for (int i = 0; i < h; i++)
		{
			for (int j = 0; j < w; j++)
			{
				used[i][j] = false;
			}
		}
		q.push(make_pair(make_pair(sy,sx), 0));
		used[sy][sx] = true;
		while (q.size() > 0)
		{
			pair<pair<int, int>, int> p = q.front(); q.pop();
			int y = p.first.first;
			int x = p.first.second;
			int c = p.second;

			if (field[y][x] == '0' + m)
			{
				sy = y;
				sx = x;
				ans += c;
				break;
			}

			for (int i = 0; i < 4; i++)
			{
				int ny = y + dy[i];
				int nx = x + dx[i];
				if (ny < 0 || nx < 0 || ny >= h || nx >= w)continue;
				if (field[ny][nx] == 'X')continue;
				if (used[ny][nx])continue;
				used[ny][nx] = true;
				pair<pair<int, int>, int> next = make_pair(make_pair(ny,nx), c + 1);
				q.push(next);
			}
		}
	}

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

C++: #include<iostream>
#include<cstdio>
#include<string>
#include<vector>
#include<map>
#include<queue>
#include<algorithm>

using namespace std;
const int INF=100000000;

typedef pair<int, int> P;

int h,w,n;
int ans=0;
int sx,sy;
int kx[10],ky[10];
long int field[1001][1001],field2[1001][1001];
char str[1001];
int dx[4]={1,0,-1,0},dy[4]={0,1,0,-1,};

int bfs(int e){
	int a=0,b=0;
	queue<P> que;
	for(a=0;a<h;a++){
		for(b=0;b<w;b++){
			field2[b][a]=INF;
		}
	}
	que.push(P(sx,sy));
	field2[sx][sy]=0;
	while(que.size()){
		P p=que.front();que.pop();
		if(p.first==kx[e] && p.second==ky[e])break;
		for(a=0;a<4;a++){
			int nx=p.first+dx[a],ny=p.second+dy[a];
			if(0<=nx && nx<w && 0<=ny && ny<h && field[nx][ny]!=-1 && field2[nx][ny]==INF){
				que.push(P(nx,ny));
				field2[nx][ny]=field2[p.first][p.second]+1;
			}
		}
	}
	return field2[kx[e]][ky[e]];
}

int main(void){
	int a,b;
	scanf("%d %d %d",&h,&w,&n);
	for(a=0;a<h;a++){
		scanf("%s",str);
		for(b=0;b<w;b++){
			if(str[b]=='S')sx=b,sy=a;
			if(str[b]=='X')field[b][a]=-1;
			else field[b][a]=0;
			if('1' <= str[b] && str[b] <= '9'){
				field[b][a]=str[b]-'0';
				kx[field[b][a]]=b;
				ky[field[b][a]]=a;
			}
		}
	}
	for(a=1;a<=n;a++){
		ans+=bfs(a);
	}
	printf("%d\n",ans);
	return 0;
}