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>
using namespace std;
typedef pair<int, int> P;
const int MAX_HW = 1000;
int n, h, w, rat, s[2], g[2], flag[MAX_HW+1][MAX_HW][2];
int town[MAX_HW][MAX_HW];
char town2[MAX_HW][MAX_HW];
queue <P> que;
P p;
void bfs(int sy, int sx){
	que.push(P(sy, sx));
	flag[sy][sx][0]=rat;
	while (que.size()){
	RE:
		p = que.front();
		que.pop();
		for (int i = -1; i <= 1; i++){
			for (int j = -1; j <= 1; j++){
				if (i == 0 || j == 0){
					if (town2[p.first + i][p.second + j] != 'X'&&flag[p.first + i][p.second + j][0] != rat&&p.first + i < h&&p.first + i >= 0 && p.second + j < w&&p.second + j >= 0) {
							flag[p.first+i][p.second+j][0] = rat;
							flag[p.first + i][p.second + j][1] = flag[p.first][p.second][1] + 1;
							if (town[p.first + i][p.second + j] == rat){
							if (rat == n) return;
							rat++;
							flag[p.first+i][p.second+j][0] = rat;
							while (que.size()){
								que.pop();
							}
							que.push(P(p.first + i, p.second + j));
							goto RE;
						}
						else{
						que.push(P(p.first + i, p.second + j));
						}
					}
				}
			}
		}
	}
}
int main(){
	cin >> h >> w >> n;
	rat = 1;
	for (int i = 0; i < h; i++){
		for (int j = 0; j < w; j++){
			cin >> town2[i][j];
			town[i][j] = town2[i][j] - 48;
			if (town2[i][j] == 'S'){
				s[0] = i;
				s[1] = j;
			}
			if (town[i][j] == n){
				g[0] = i;
				g[1] = j;
			}
		}
	}
	bfs(s[0], s[1]);
	cout << flag[g[0]][g[1]][1] << endl;
	return 0;
}

C++: #include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <vector>
#include <utility>
#include <functional>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <deque>
 
using namespace std;
 
#define rep(i,n) for(int i=0; i<(n); i++)
#define repc(i,s,e) for(int i=(s); i<(e); i++)
#define pb(n) push_back((n))
#define mp(n,m) make_pair((n),(m))
#define all(r) r.begin(),r.end()
#define fi first
#define se second
 
 
typedef long long ll;
typedef vector<int> vi;
typedef vector<vi> vii;
typedef vector<ll> vl;
typedef vector<vl> vll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;


const int INF=1e9;

int dx[]={-1,0,1,0};
int dy[]={0,-1,0,1};
int h, w, n;
vector<string> s;

int bfs(pii st, pii g){
	vector<vector<int> > v(h, vi(w, 0));
	queue<pair<pii, int> > q;
	pair<pii, int> p(st, 0);
	q.push(p);
	while(!q.empty()){
		p=q.front();
		q.pop();
		v[p.fi.fi][p.fi.se]=1;
		if(g == p.fi){
			return p.se;
		}
		for(int i = 0; i < 4; i++){
			int y = p.fi.fi+dy[i], x = p.fi.se+dx[i];
			if(y < 0 || y >= h || x < 0 || x >= w ||s[y][x]=='X' || v[y][x]) continue;
			q.push(pair<pii,int>(pii(y, x), p.se+1));
		}
	}
	return -1;
}

int main(){
	cin>>h>>w>>n;
	s = vector<string>(h);
	rep(i, h) cin>>s[i];
	vector<pii> p(n+1);
	for(int i = 0; i < h; i++){
		for(int j = 0; j < w; j++){
			if(s[i][j]=='S'){
				p[0] = pii(i, j);
			}
			else if(s[i][j]>='1'&&s[i][j]<='9'){
				p[s[i][j]-'0'] = pii(i, j);
			}
		}
	}
	
	int ans = 0;
	for(int i = 0; i < n; i++){
		ans += bfs(p[i], p[i+1]);
	}
	cout<<ans<<endl;
}

C++: //#include "stdafx.h"
//
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <map>
#include <set>
#include <bitset>
#include <cmath>
#include <string>
#include <cstring>
#include <iterator>
#define FI first
#define SE second
#define PF push_front
#define PB push_back
#define POF pop_front
#define POB pop_back
#define MA make_pair
#define ll long long
#define VE vector<int>
#define VP vector<pair<int,int> >
#define FOR(i,a,b) for(int i=a;i<b;i++)
#define ROF(i,a,b) for(int i=b-1;i>=a;i--)
#define YES(i) cout<<(i?"YES":"NO")<<endl
#define Yes(i) cout<<(i?"Yes":"No")<<endl
using namespace std;
//
const int INF = 1e9 + 7;
const int mod = 1e9 + 7;
//
int H, W, N;
char M[1000][1000];
pair<int, int> n[10];
bool used[1000][1000];
int dx[4] = { 0,-1,0,1 }, dy[4] = { -1,0,1,0 };
//
int BFS(int num) {
    int sx = n[num - 1].FI, sy = n[num - 1].SE;
    int gx = n[num].FI, gy = n[num].SE;
    deque<pair<pair<int,int> , int> > que;
    que.PB(MA(MA(sx,sy),0));
    FOR(i, 0, H) {
        FOR(j, 0, W) {
            used[i][j] = false;
        }
    }
    used[sx][sy] = true;
    while (!que.empty()) {
        pair<pair<int,int> , int> P= que.front();
        que.pop_front();
        if (P.FI.FI == gx&&P.FI.SE==gy) {
            return P.SE;
        }
        FOR(i, 0, 4) {
            int nx = P.FI.FI + dx[i], ny = P.FI.SE + dy[i];
            if (0 <= nx && nx < H && 0 <= ny && ny < W && !used[nx][ny] && M[nx][ny] != 'X') {
                que.PB(MA(MA(nx, ny), P.SE + 1));
                used[nx][ny] = true;
            }
        }
    }
}
int main() {
    cin >> H >> W >> N;
    FOR(i, 0, H) {
        FOR(j, 0, W) {
            cin >> M[i][j];
            if (M[i][j]=='S') {
                n[0] = MA(i, j);
            }
            else if ('1' <= M[i][j] && M[i][j] <= '9') {
                n[M[i][j] - '0'] = MA(i, j);
            }
        }
    }
    int ans = 0;
    FOR(i, 1, N + 1) {
        ans += BFS(i);
    }
    cout << ans << endl;
    return 0;
}

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

  int used[1001][1001];
  char m[1001][1001];
  int H,W,N,sx,sy;
  
  const int dx[4]={1,0,-1,0};
  const int dy[4]={0,1,0,-1};

bool check(int x,int y){
  return x>=0&&y>=0&&x<H&&y<W&&m[x][y]!='X';
}

void debug()
{
  for(int i = 0; i < H; i++) {
    for(int j = 0; j < W; j++){
      printf("%3d", used[i][j]);
    }
    puts("");
  }
  puts("");
} 
int bfs(int p){
  for(int i = 0; i < 1001; i++)for(int j=0;j<1001;j++)used[i][j] = 0;
  queue<pair<int,int> > que;
  que.push(make_pair(sx,sy));
  while(!que.empty()){
    pair<int,int> pos= que.front();
    que.pop();
    for(int i=0;i<4;i++){
      int x=pos.first+dx[i];
      int y=pos.second+dy[i];
      if(check(x,y) && used[x][y] == 0){
       que.push(make_pair(x,y));
       used[x][y] = used[pos.first][pos.second] + 1;
      }
      if(m[x][y]==p+'0'){
	
       sx=x;
       sy=y;
       return used[x][y];
      }
    }
  }
}



int main()
{
  cin>>H>>W>>N;
  for(int i=0;i<H;i++){
    for(int j=0;j<W;j++){
      cin>>m[i][j];
      if(m[i][j]=='S'){
       sx=i;
       sy=j;
      }	
    }
  }
  int res=0;
  for(int i=1;i<=N;i++){
    res+=bfs(i);
  }
  cout << res << endl;
  
}