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>

#define MAX_W 1000
#define MAX_H 1000
#define MAX_N 1000
#define INF -1

typedef std::pair<int, int> P;

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

int w, h, n;
int sx, sy, gx[MAX_N], gy[MAX_N];
char field[MAX_W][MAX_H];

int solve(int _sx, int _sy, int _gx, int _gy);

int main(){
    std::cin >> h >> w >> n;
    for(int i = 0; i < h; ++i){
        for(int j = 0; j < w; ++j){
            std::cin >> field[j][i];
            if(field[j][i] == 'S')
                sx = j, sy = i;
            
            else if(field[j][i] >= '0' && field[j][i] <= '9')
                gx[field[j][i] - '0'] = j, gy[field[j][i] - '0'] = i;
        }
    }
    
    int ans = 0;
    
    for(int i = 0; i < n; ++i){
        if(i == 0)
            ans += solve(sx, sy, gx[i + 1], gy[i + 1]);
        else
            ans += solve(gx[i], gy[i], gx[i + 1], gy[i + 1]);
    }
    
    std::cout << ans << std::endl;
    
    return 0;
}

int solve(int _sx, int _sy, int _gx, int _gy){
    int dis[MAX_W][MAX_H];
    std::queue<P> que;
    que.push(P(_sx, _sy));
    
    for(int i = 0; i < h; ++i){
        for(int j = 0; j < w; ++j)
            dis[j][i] = INF;
    }
    
    dis[_sx][_sy] = 0;
    
    while(que.size()){
        P p = que.front();
        que.pop();
        
        if(p.first == _gx && p.second == _gy)
            break;
        
        for(int i = 0; i < 4; ++i){
            int nx = p.first + dx[i], ny = p.second + dy[i];
            
            if(nx >= 0 && ny >= 0 && nx < w && ny < h && field[nx][ny] != 'X' && dis[nx][ny] == INF){
                que.push(P(nx, ny));
                dis[nx][ny] = dis[p.first][p.second] + 1;
            }
        }
    }
    
    return dis[_gx][_gy];
}

C++: #include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <climits>
#include <cfloat>
#include <ctime>
#include <map>
#include <utility>
#include <set>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
#include <sstream>
#include <complex>
#include <stack>
#include <queue>
#include <numeric>

using namespace std;

#ifdef _MSC_VER
#define __typeof__ decltype

template <class T>
int __builtin_popcount(T n) { return n ? 1 + __builtin_popcount(n & (n - 1)) : 0; }
#endif

#define foreach(it, c) for (__typeof__((c).begin()) it=(c).begin(); it != (c).end(); ++it)
#define all(c) (c).begin(), (c).end()
#define rall(c) (c).rbegin(), (c).rend()
#define popcount __builtin_popcount

#define rep(i, n) for (int i = 0; i < n; ++i)

template <class T> void max_swap(T& a, const T b) { a = max(a, b); }
template <class T> void min_swap(T& a, const T b) { a = min(a, b); }

const double EPS = 1e-10;
typedef long long ll;
typedef pair<int, int> pint;


int main()
{
	int h, w, n;
	scanf("%d%d%d", &h, &w, &n);
	static char c[1024][1024];
	rep(i, h)
		scanf("%s", c[i]);
	
	int px[10], py[10];
	rep(i, h)
	{
		rep(j, w)
		{
			if (c[i][j] == 'S')
				c[i][j] = '0';
			if (isdigit(c[i][j]))
			{
				px[c[i][j] - '0'] = j;
				py[c[i][j] - '0'] = i;
			}
		}
	}

	const int INF = 1 << 25;
	const int dx[] = { 0, 1, 0, -1 };
	const int dy[] = { 1, 0, -1, 0 };

	int dis[10];
	rep(s, n)
	{
		static int d[1024][1024];
		rep(i, h)
			rep(j, w)
			d[i][j] = INF;
		int sx = px[s], sy = py[s];
		int gx = px[s + 1], gy = py[s + 1];

		queue<pint> q;
		d[sy][sx] = 0;
		q.push(pint(sx, sy));
		while (!q.empty())
		{
			pint t = q.front(); q.pop();
			int x = t.first, y = t.second;

			int next = d[y][x] + 1;
			rep(i, 4)
			{
				int tx = x + dx[i], ty = y + dy[i];
				if (0 <= tx && tx < w && 0 <= ty && ty < h
					&& c[ty][tx] != 'X' && next < d[ty][tx])
				{
					d[ty][tx] = next;
					q.push(pint(tx, ty));
					if (tx == gx && ty == gy)
					{
						q = queue<pint>();
						break;
					}
				}
			}
		}
		dis[s] = d[gy][gx];
	}
	printf("%d\n", accumulate(dis, dis + n, 0));
}

C++: #include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;

#define sf scanf
#define pf printf
#define pb push_back
#define lb lower_bound
#define forr(i,x,y) for(int i=x;i<=y;i++)
#define ford(i,x,y) for(int i=x;i>=y;i--)

const int inf=0x7f7f7f,mod=100000000;

inline void read(int &input) {
	int value=0,sign=1;
	char ch;
	do {
		ch=getchar();
		if(ch=='-') sign*=-1;
	}while(ch<'0'||ch>'9');
	while(ch>='0'&&ch<='9') {
		value=value*10+ch-'0';
		ch=getchar();
	}
	input=value*sign;
}

inline void read(int *input,int begin,int end) {
	for(int i=begin;i<=end;i++)
		read(input[i]);
}

inline void read(int &input1,int &input2) {
	read(input1),read(input2);
}

inline void read(int &input1,int &input2,int &input3) {
	read(input1,input2),read(input3);
}

inline void read(int &input1,int &input2,int &input3,int &input4) {
	read(input1,input2),read(input3,input4);
}

int h,w,n,ans;
char mp[1008][1008];
bool passed[1008][1008];
struct node{
    int r,c,res;
}que[1000000];
int head=0,tail=1;
int x[]={0,0,1,-1};
int y[]={1,-1,0,0};

void bfs(char ch) {
	head=0,tail=1;
	que[0].res=0;
    passed[que[0].r][que[0].c]=1;
    while(head!=tail) {
        node Head=que[head];
        forr(i,0,3) {
            node Tail=Head;
            Tail.r+=x[i];
            Tail.c+=y[i];
            Tail.res++;
            if(Tail.r<=0||Tail.c<=0||Tail.r>h||Tail.c>w) continue;
            if(mp[Tail.r][Tail.c]=='X'||passed[Tail.r][Tail.c]) continue;
            que[tail++]=Tail;
            passed[Tail.r][Tail.c]=1;
            if(mp[Tail.r][Tail.c]==ch) {
                ans+=Tail.res;
                que[0].r=Tail.r;
                que[0].c=Tail.c;
            }
        }
        head++;
    }
}

int main() {
	read(h,w,n);
	forr(i,1,h) {
		sf("%s",mp[i]+1);
		forr(j,1,w)
			if(mp[i][j]=='S')
				que[0].r=i,que[0].c=j;
	}
	forr(i,1,n)
        memset(passed,0,sizeof passed),
		bfs('0'+i);
	cout<<ans<<endl;
	return 0;
}