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 <algorithm>
#include <string>
#include <vector>
#include <map>
#include <sstream>
#include <functional>
#include <numeric>
#include <cmath>
#include <cstring>
#include <cstdio>
#include <queue>
#include <stack>
#include <set>

using namespace std;

#define ALL(co) co.begin(), co.end()
#define tpl(...) make_tuple(__VA_ARGS__)

typedef long long LL;
typedef pair<int, int> P; typedef pair<P, int> PI; typedef pair<P, P> PP;
typedef vector<int> Array; typedef vector<vector<int> > Array2;
typedef vector<LL> LArray; typedef vector<P> PArray; typedef vector<string> SArray;

const int INF = 1 << 29;
const LL LINF = 1LL << 60;

inline int getInt() { int itiv; return (cin >> itiv, itiv); }
template <typename T> void readAll(vector<T>& vec) { for (int i = 0, size = vec.size(); i < size; i++) cin >> vec[i]; }
template <typename T, typename U> void readAll(vector<pair<T, U> >& vec) { for (int i = 0, size = vec.size(); i < size; i++) cin >> vec[i].first >> vec[i].second; }
template < typename T > inline string toString( const T &a ){ ostringstream oss; oss << a; return oss.str(); };
inline bool between(int min, int max, int n) { return min <= n && n <= max; }
inline bool inRange(int begin, int end, int n) { return begin <= n && n < end; }
inline bool inRange(int size, int n) { return 0 <= n && n < size; }

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

int h, w, n;

int main(void)
{
	ios::sync_with_stdio(false);
	while(cin >> h >> w >> n && n)
	{
		vector<vector<char> > stage(h, vector<char>(w));
		PArray goals(n + 1);
		for (int i = 0; i < h; i++)
		{
			for (int j = 0; j < w; j++)
			{
				cin >> stage[i][j];
				if(stage[i][j] == 'S') goals[0] = P(i, j);
				int num = stage[i][j] - '0';
				if(inRange(n + 1, num)) goals[num] = P(i, j);
			}
		}

		int ans = 0;
		for (int i = 0; i < n; i++)
		{
			P start = goals[i], goal = goals[i + 1];
			vector<vector<bool> > visited(h, vector<bool>(w));
			queue<PI> que;
			que.push(PI(start, 0));
			while (!que.empty())
			{
				PI pi = que.front(); que.pop();
				if(goal == pi.first)
				{
					ans += pi.second;
					break;
				}
				int r = pi.first.first, c = pi.first.second;
				visited[r][c] = true;

				for (int i = 0; i < 4; i++)
				{
					int nr = r + dr[i], nc = c + dc[i];
					if(!inRange(h, nr) || !inRange(w, nc) || stage[nr][nc] == 'X' || visited[nr][nc]) continue;
					que.push(PI(P(nr, nc), pi.second + 1));
				}
			}
		}
		cout << ans << endl;
	}
	return 0;
}

C++: //
//  main.cpp

#include <iostream>
#include <queue>
using namespace std;
using ll = long long;
const ll MAX = 10000000000000;
int h,w,n;
bool matrix[1001][1001]={{}};
bool visited[1001][1001]={{}};
pair<int,int> target;
struct state{
	int x;
	int y;
	int depth;
};

ll min(ll x,ll y){
	if(x < y){
		return x;
	}else{
		return y;
	}
}

/*

ll dfs(ll depth,int x,int y){
	if(!matrix[x][y])return MAX;
	if(target.first == x && target.second == y)return depth;
	
	ll a,b,c,d;
	a = b = c = d = MAX;
	if(!visited[x+1][y]){
		visited[x+1][y] = true;
		a = dfs(depth+1,x+1,y);
		visited[x+1][y] = false;
	}
	if(!visited[x-1][y]){
		visited[x-1][y] = true;
		b = dfs(depth+1,x-1,y);
		visited[x-1][y] = false;
	}
	if(!visited[x][y+1]){
		visited[x][y+1] = true;
		c = dfs(depth+1,x,y+1);
		visited[x][y+1] = false;
	}
	if(!visited[x][y-1]){
		visited[x][y-1] = true;
		d = dfs(depth+1,x,y-1);
		visited[x][y-1] = false;
	}
	return min(a,min(b,min(c,d)));
}
*/
ll bfs(int x,int y){
	queue<state> willvisit;
	willvisit.push({x,y,0});
	ll ret;
	while(1){
		if(willvisit.empty())break;
		state now = willvisit.front();
		willvisit.pop();
		
		if(now.x == target.first && now.y == target.second){
			ret = now.depth;
			break;
		}
		if(!visited[now.x+1][now.y]){
			if(matrix[now.x+1][now.y]){
				visited[now.x+1][now.y] = true;
				willvisit.push({now.x+1,now.y,now.depth+1});
			}
		}
		if(!visited[now.x-1][now.y]){
			if(matrix[now.x-1][now.y]){
				visited[now.x-1][now.y] = true;
				willvisit.push({now.x-1,now.y,now.depth+1});
			}
		}
		if(!visited[now.x][now.y+1]){
			if(matrix[now.x][now.y+1]){
				visited[now.x][now.y+1] = true;
				willvisit.push({now.x,now.y+1,now.depth+1});
			}
		}
		if(!visited[now.x][now.y-1]){
			if(matrix[now.x][now.y-1]){
				visited[now.x][now.y-1] = true;
				willvisit.push({now.x,now.y-1,now.depth+1});
			}
		}
	}
	
	return ret;
}

void visitedReset(){
	for(int i=0;i<1001;i++){
		for(int j=0;j<1001;j++){
			visited[i][j] = false;
		}
	}
}

int main(){
	for(int i=0;i<1001;i++){
		for(int j=0;j<1001;j++){
			matrix[i][j] = visited[i][j] = false;
		}
	}
	
	cin >> h >> w >> n;
	pair<int,int> cheese[10];
	for(int i=1;i<=h;i++){
		for(int j=1;j<=w;j++){
			char input;
			cin >> input;
			switch(input){
				case '.':
					matrix[i][j] = true;
					break;
				case 'X':
					matrix[i][j] = false;
					break;
				case 'S':
					matrix[i][j] = true;
					cheese[0] = make_pair(i,j);
					break;
				default:
					matrix[i][j] = true;
					cheese[input - '0'] = make_pair(i,j);
					break;
			}
		}
	}
	
	ll answer=0;
	for(int i=0;i<n;i++){
		target = cheese[i+1];
		visited[cheese[i].first][cheese[i].second] = true;
		answer += bfs(cheese[i].first,cheese[i].second);
		visitedReset();
	}
	/*
	for(int i=0;i<n;i++){
		target = cheese[i+1];
		visited[cheese[i].first][cheese[i].second] = true;
		answer += dfs(0,cheese[i].first,cheese[i].second);
		visited[cheese[i].first][cheese[i].second] = false;
	}
	*/
	cout << answer << endl;
	return 0;
}