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++: // clang-format off
#include <bits/stdc++.h>
#define int long long
#define main signed main()
// #define main int main()
#define loop(i, a, n) for (int i = (a); i < (n); i++)
#define rep(i, n) loop(i, 0, n)
#define all(v) (v).begin(), (v).end()
#define rall(v) (v).rbegin(), (v).rend()
#define prec(n) fixed << setprecision(n)
#define stlice(from, to) substr(from, (to) - (from) + 1)
#define pb push_back
#define mp make_pair
#define mt make_tuple
#define fi first
#define se second
using namespace std;
typedef pair<int, int> pii;
typedef vector<int> vi;
typedef vector<double> vd;
typedef vector<char> vc;
typedef vector<bool> vb;
typedef vector<string> vs;
typedef vector<pii> vpii;
typedef vector<vi> vvi;
typedef vector<vb> vvb;
typedef vector<vpii> vvpii;
const int INF = sizeof(int) == sizeof(long long) ? 1000000000000000000LL : 1000000000;
const int MOD = 1000000007;
const double PI = acos(-1);
template<typename A, typename B> bool cmin(A &a, const B &b) { return a > b ? (a = b, true) : false; }
template<typename A, typename B> bool cmax(A &a, const B &b) { return a < b ? (a = b, true) : false; }
bool odd(const int &n) { return n & 1; }
bool even(const int &n) { return !odd(n); }
void solve();
main { solve(); return 0; }
// clang-format on

typedef pair<pii, int> ppi;

int di[] = {1, 0, -1, 0}, dj[] = {0, 1, 0, -1};

void solve() {
  int h, w, n;
  cin >> h >> w >> n;
  vs s(h);
  vpii v(n + 1);
  rep(i, h) {
    cin >> s[i];
    rep(j, w) {
      if (s[i][j] == 'S') v[0]                               = mp(i, j);
      if ('1' <= s[i][j] && s[i][j] <= '9') v[s[i][j] - '0'] = mp(i, j);
    }
  }
  int c    = 0;
  auto bfs = [&](vs s, pii f, pii t) {
    queue<ppi> q;
    q.push(mp(f, 0));
    while (q.size()) {
      int i = q.front().fi.fi, j = q.front().fi.se, d = q.front().se;
      q.pop();
      if (i < 0 || j < 0 || i >= h || j >= w || s[i][j] == 'X') continue;
      if (i == t.fi && j == t.se) return d;
      s[i][j] = 'X';
      d++;
      rep(k, 4) q.push(mp(mp(i + di[k], j + dj[k]), d));
    }
  };
  loop(i, 1, v.size()) c += bfs(s, v[i - 1], v[i]);
  cout << c << endl;
}

C++: #include<bits/stdc++.h>
#define int long long int

using namespace std;

const int INF = 1000000009;

typedef pair<int ,int> P;
char masu[1003][1003];
int W,H,K,ans=0;
int sx[10],sy[10];
int gx[10],gy[10];

int d[1003][1003];

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

void sho(){
    for(int i=0;i<H;i++){
        for(int j=0;j<W;j++){
            d[j][i]=INF;
        }
    }
}

int bfs(){
    queue<P> que;
    for(int i=1;i<=K;i++){
        sho();
        que.push(P(sx[i],sy[i]));
        d[sx[i]][sy[i]]=0;
        while(que.size()){
            P p=que.front();que.pop();
            if(p.first==gx[i]&&p.second==gy[i])break;
            for(int j=0;j<4;j++){
                int nx = p.first+dx[j],ny = p.second+dy[j];
                if(0<=nx&nx<W&&0<=ny&&ny<H&&masu[nx][ny]!='#'&&d[nx][ny]==INF){
                    que.push(P(nx,ny));
                    d[nx][ny] = d[p.first][p.second] + 1;
                }
            }
        }ans+=d[gx[i]][gy[i]];
    }
    return ans;
}

signed main(){
    cin >> H >> W >> K;
    for(int i=0;i<H;i++){
        for(int j=0;j<W;j++){
            cin >> masu[j][i];
            if(isdigit(masu[j][i])){
                int a=masu[j][i]-'0';
                gx[a]=j,gy[a]=i,sx[a]=j,sy[a]=i;
            }
        }
    }
    int answer = bfs();
    cout << answer << endl;
return 0;
}

C++: #include<bits/stdc++.h>
#define x first
#define y second
#define rep(i,a,b) for(int i=a;i<b;i++)
using namespace std;pair<int,int> p[12];bool t[1010][1010],v[1010][1010];queue<pair<int,pair<int,int> > >Q;int main(){int h,w,k,a=0,dx[]={0,1,0,-1},dy[]={1,0,-1,0};cin>>h>>w>>k;rep(i,0,h)rep(j,0,w){t[i][j]=true;char z;cin>>z;if(z=='X')t[i][j]=0;if(z=='S')p[0]=make_pair(i,j);if(z>'0'&&z<='9')p[z-'0']=make_pair(i,j);}rep(r,0,k){Q.push(make_pair(0,p[r]));rep(i,0,h)rep(j,0,w)v[i][j]=0;v[p[r].x][p[r].y]=1;while(1){int L=Q.front().x,Y=Q.front().y.x,X=Q.front().y.y;if(Y==p[r+1].x&&X==p[r+1].y){a+=L;break;}rep(i,0,4){int f=Y+dy[i],g=X+dx[i];if(f+1&&f<h&&g+1&&g<w)if(t[f][g]==1&&vis[f][g]==0)v[f][g]=1;Q.push(make_pair(L+1,make_pair(f,g)));}Q.pop();}while(!Q.empty())Q.pop();}cout<<a<<endl;return 0;}

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 ] ;

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 ;
}