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 1000

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

int h,w,N,PX[4]={1,-1,0,0},PY[4]={0,0,1,-1},sum=0;
char ch[MAX][MAX];

void bfs(P p,P q){
	std::queue<P> Q;
	Q.push(p);
	while(!Q.empty()){
		P u=Q.front();Q.pop();
		for(int i=0;i<4;++i){
			if(u.first+PX[i]>=0&&u.first+PX[i]<h&&u.second+PY[i]<w&&u.second+PY[i]>=0&&ch[u.first+PX[i]][u.second+PY[i]]!='X'){
				if(P(u.first+PX[i],u.second+PY[i])==q)
					return;
				else{
					++sum;
					Q.push(P(u.first+PX[i],u.second+PY[i]));
				}
			}
		}
	}
}

void solve(){
	int n=1;
	P s,p[10];
	for(int i=0;i<h;++i){
		for(int j=0;j<w;++j){
			if(ch[i][j]=='S')
				s.first=i;s.second=j;
			if(ch[i][j]==char(n)){
				p[n]=P(i,j);
				++n;
			}
		}
	}
	bfs(s,p[1]);
	for(int i=1;i<9;++i){
		bfs(p[i],p[i+1]);
	}
}

int main(){
	std::cin>>h>>w>>N;
	for(int i=0;i<h;++i){
		for(int j=0;j<w;++j){
			std::cin>>ch[i][j];
		}
	}
	solve();
	std::cout<<sum<<std::endl;
	return 0;
}

C++: #include <iostream>
#include <vector>
#include <algorithm>
#include <stack>
#include <queue>
#include <string>
#include <map>
#include <functional>
#include <cmath>
#include <cstdio>
using namespace std;

const int INF = 100000000;
typedef pair<int, int> P;
int sx, sy;

char _map[1000][1001];
int H, W;
char N;
char n = '1';

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

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

int bfs(){
  int ans = 0;
  queue<P> que;
  init();
  que.push(P(sx, sy));
  d[sx][sy] = 0;

  while(que.size()){
    P p = que.front(); que.pop();
    if(_map[p.first][p.second] == n){
      if(n == N){
        ans += d[p.first][p.second];
        break;
      }else{
        ans += d[p.first][p.second];
        init();
        queue<P> empty;
        swap(que, empty);
        sx = p.first; sy = p.second;
        d[sx][sy] = 0;
        n++;
      }
    }
    for(int i = 0; i < 4; i++){
      int nx = p.first + dx[i], ny = p.second + dy[i];

      if(0 <= nx && nx < H && 0 <= ny && ny < W && _map[nx][ny] != 'X' && d[nx][ny] == INF){
        que.push(P(nx, ny));
        d[nx][ny] = d[p.first][p.second] + 1;
      }
    }
  }
  return ans;
}

void solve(){
  int res = bfs();
  cout << res << endl;
}

int main(){
  cin >> H >> W >> N;
  for(int i = 0; i < H; i++){
    for(int j = 0; j < W; j++){
      cin >> _map[i][j];
      if(_map[i][j] == 'S'){
        sx = i; sy = j;
      }
    }
  }
  solve();
}

C++: #include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cfloat>
#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 <cstring>
#include <sstream>
#include <cassert>
using namespace std;
static const double EPS = 1e-10;
typedef long long ll;
typedef pair<int,int> PI;
#define rep(i,n) for(int i=0;i<(int)n;++i)
#define FOR(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i)
#define ALL(c) (c).begin(), (c).end()
#define mp(a,b) make_pair(a,b)
#define pb(a) push_back(a)
int dx[]={0,1,0,-1},dy[]={1,0,-1,0};

typedef struct{
  short x,y;
  int cost;
  short ch;
}mouse;

short maxch[1000][1000];
char ku[1000][1000];
mouse t;
short cx,cy,nx,ny,ch,nch,h,w,n,cost;

main(){
  //scanf("%d%d%d",&h,&w,&n);
  cin>>h>>w>>n;
  rep(i,h)scanf("%s",ku[i]);


  rep(i,h)rep(j,w){
    if(ku[i][j]=='S')cx=i,cy=j;
    maxch[i][j]=-1;
  }

  queue<mouse> Q;

  Q.push((mouse){cx,cy,0,0});
  maxch[cx][cy]=0;

  while(!Q.empty()){
    //cout<<Q.size()<<endl;
    t=Q.front();Q.pop();
    cx=t.x,cy=t.y,cost=t.cost;
    ch=t.ch;

    rep(i,4){
      nx=cx+dx[i],ny=cy+dy[i];
      if(nx<0 || nx>=h || ny<0 || ny>=w)continue;
	 if(ku[nx][ny]=='X')continue;
	 nch=ch;
	 if(ku[nx][ny]<='9' && ku[nx][ny]>='1' && ku[nx][ny]-'0'==t.ch+1){
	   nch=ch+1;
	 }

	 if(maxch[nx][ny]>=nch)continue;
	 if(nch==n){
	   printf("%d\n",cost+1);
	   return 0;
	 }
	 maxch[nx][ny]=nch;
	 Q.push((mouse){nx,ny,cost+1,nch});
    }
  }
}

C++: #include <bits/stdc++.h>
using namespace std;

#define int				long long
#define FOR( i, m, n )  for( int (i) = (m); (i) < (n); (i)++ )
#define REP( i, n )     FOR( i, 0, n )
#define REPR( i, m )	for( int (i) = (m); (i) >= 0; (i)-- )
#define REPONE( i, n )	FOR( i, 1, n + 1 )
#define ALL( a )        (a).begin(), (a).end()
#define P				pair<int, int>
#define MP				make_pair

template<class T>bool chmax( T& a, const T& b ) { if( a < b ) { a = b; return 1; } return 0; }
template<class T>bool chmin( T& a, const T& b ) { if( a > b ) { a = b; return 1; } return 0; }

const int INF = 1e9;
const int MOD = 1e9 + 7;

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

char city[1001][1001];
int d[1001][1001];
char goal = '1';
int H, W, N;

P bfs( P& s ) {
	fill( d[0], d[1001], INF );
	d[s.first][s.second] = 0;

	queue<P> que;
	que.push( s );
	while( !que.empty() ) {
		P p = que.front(); que.pop();
		if( city[p.first][p.second] == goal ) return p;

		REP( i, 4 ) {
			P now( p.first + dx[i], p.second + dy[i] );
			if( now.first >= 0 && now.first < W && now.second >= 0 && now.second < H && city[now.first][now.second] != 'X' && d[now.first][now.second] == INF ) {
				que.push( now );
				d[now.first][now.second] = d[p.first][p.second] + 1;
			}
		}
	}
}

signed main() {
	cin >> H >> W >> N;
	P s;
	REP( i, H ) {
		REP( j, W ) {
			cin >> city[j][i];
			if( city[j][i] == 'S' ) {
				s.first = j;
				s.second = i;
				city[j][i] = '.';
			}
		}
	}

	int ans = 0;
	REP( i, N ) {
		P t = bfs( s );
		ans += d[t.first][t.second];
		s = t;
		goal++;
	}


	cout << ans << endl;
}