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<utility>
using namespace std;

const int INF = 2000000;
char fl[1010][1010];
int d[1010][1010];

int bfs(int sx, int sy, int gx, int gy, int mx, int my) {
	typedef pair<int, int>P;
	int dx[4] = { 1,0,-1,0 }, dy[4] = { 0,1,0,-1 };

	for (int i = 0;i < mx;i++)
		for (int j = 0;j < my;j++)d[i][j] = INF;

	queue<P>que;
	que.push(P(sx, sy));
	d[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 (0 <= nx&&nx < my && 0 <= ny&&ny < mx&&fl[nx][ny] != 'X'&&d[nx][ny] == INF) {
				que.push(P(nx, ny));
				d[nx][ny] = d[p.first][p.second] + 1;
			}
		}
	}
	return d[gx][gy];
}

int main() {
	int h, w, n;
	cin >> h >> w >> n;
	int al = 0;
	for (int i = 0;i < h;i++) {
		for (int j = 0;j < w;j++) { cin >> fl[i][j]; 
		}
	}
	char a[10] = { 'S','1','2','3','4','5','6','7','8','9' };
	for (int i = 0;i < n;i++) {
		int sx, sy;
		int gx, gy;
		for (int j = 0;j < h;j++) {
			for (int k = 0;k < w;k++) {

				if (fl[j][k]== a[i]) {
					sx = j;
					sy = k;
				}
				if (fl[j][k]== a[i+1]) {
					gx = j;
					gy = k;
				}
			}
		}

		al += bfs(sx, sy, gx, gy,w ,h);
	}
	cout << al << endl;
	getchar();
	getchar();
	return 0;
}

C++: #include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#include<deque>
#include<map>
#include<set>
#include<string>
#include<sstream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<cctype>
#include<climits>
using namespace std;
#define REP(i, j) for(int i = 0; i < j; i++)
#define FOR(i, j, k) for(int i = j; i < k; i++)
#define P pair<int, int>
const int INF = INT_MAX / 2;

int h, w, n;

bool CanMove(int y, int x, vector< vector<char> > m){
    if(y < 0) return false;
    if(x < 0) return false;
    if(y >= h) return false;
    if(x >= w) return false;
    if(m[y][x] == 'X') return false;
    return true;
}

//vector< vector<int> > MakeAnsMap(int y, int x, int step, vector< vector<int> > ans_map, vector< vector<char> > m){
//    ans_map[y][x] = step;
//    int my[] = {0, 0, 1, -1};
//    int mx[] = {1, -1, 0, 0};
//
//    REP(i, 4){
//        int ny = y + my[i];
//        int nx = x + mx[i];
//        if(CanMove(ny, nx, m) && ans_map[ny][nx] > step + 1){
//            ans_map = MakeAnsMap(ny, nx, step + 1, ans_map, m);
//        }
//    }
//    return ans_map;
//}

class C{
    public:
    int y, x, step;
    C(int _y, int _x, int _step);
};

C::C(int _y, int _x, int _step){
    y = _y;
    x = _x;
    step = _step;
}

vector< vector<int> > MakeAnsMap(int y, int x, int tmp, vector< vector<char> > m){
    queue<C> open;
    open.push( C(y, x, tmp) );
    vector< vector<int> > closed(m.size(), vector<int>(m[0].size()));
    REP(i, m.size()) REP(j, m[0].size()) closed[i][j] = INF;
    int my[] = {0, 0, 1, -1};
    int mx[] = {1, -1, 0, 0};

    while(!open.empty()){
        C now = open.front();
        open.pop();
        closed[now.y][now.x] = now.step;

        REP(i, 4){
            int ny = now.y + my[i], nx = now.x + mx[i];
            if(CanMove(ny, nx, m) && closed[ny][nx] > now.step + 1){
                open.push( C(ny, nx, now.step + 1) );
            }
        }
    }
    return closed;
}

int main(){
    cin >>h >>w >>n;
    vector< vector<char> > m(h, vector<char>(w) );
    vector<int> y(n + 2), x(n + 2);

    //start of input
    REP(i, h){
        REP(j, w){
            cin >>m[i][j];
            if(m[i][j] == 'S'){
                y[0] = i;
                x[0] = j;
            }
            if(m[i][j] - '0' > 0 && m[i][j] - '0' <= n){
                int num = m[i][j] - '0';
                y[num] = i;
                x[num] = j;
            }
        }
    }
    //end of input

    vector< vector<int> > ans_map(h, vector<int>(w, INF) );
    ans_map = MakeAnsMap(y[0], x[0], 0, m);

    FOR(i, 1, n + 1){
        int tmp = ans_map[y[i]][x[i]];
        REP(j, h){
            REP(k, w){
                ans_map[j][k] = INF;
            }
        }
        ans_map = MakeAnsMap(y[i], x[i], tmp, m);

    }
    cout <<ans_map[y[n]][x[n]] <<endl;
    return 0;
}

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));
  pii pos;
  rep(i,W){
    rep(j,H){
      cin >> c ;
      area[j][i] = c;
      if(c == 'S'){
        pos = make_pair(j,i);
        ++n;
      }
    }
  }
  queue<pii> q;
  q.push(pos);
  maps[pos.fi][pos.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 = vector<vector<int>>(H,vector<int>(W,inf));
          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;
}