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 <iterator>
#include <list>
#include <map>
#include <queue>
#include <bitset>
#include <fstream>
#include <cmath>
#include <ctime>
using namespace std;
typedef long long ll;

class CPoint
{
public:

	int x, y;

	CPoint() : x(0), y(0){};
	CPoint(int ax, int ay) : x(ax), y(ay){};

	bool operator==(const CPoint& obj);
	bool operator!=(const CPoint& obj);

	CPoint  operator+(const CPoint& obj);
};


class CPoint;

const int MAX_H = 1000;
const int MAX_W = 1000;
const ll  INF	= 1000000000;

char field[MAX_H][MAX_W];
bool used[MAX_H][MAX_W];
ll	 d[MAX_H][MAX_W];
int  H, W, N;

ll getroad(CPoint start, CPoint goal);


int main()
{
	cin>>H>>W>>N;
	vector<CPoint> factorys(N+1);

	for(int i = 0; i < H; i++){
		for(int j = 0; j < W; j++){
			cin>>field[i][j];
			if(field[i][j] != 'X' && field[i][j] != '.'){
				if(field[i][j] == 'S')	factorys[0] = CPoint(i, j);
				else					factorys[field[i][j] - '0'] = CPoint(i, j);
			}
		}
	}

	ll res = 0;
	for(int i = 0; i < N; i++)
		res += getroad(factorys[i], factorys[i+1]);

	cout<<res<<endl;
}

ll getroad(CPoint start, CPoint goal)
{
	for(int i = 0; i < H; i++) for(int j = 0; j < W; j++) d[i][j] = INF;

	queue<CPoint> que;
	que.push(start);
	d[start.x][start.y] = 0;

	while(!que.empty()){
		CPoint v = que.front();
		que.pop();
		if(v.y+1 < W  && field[v.x][v.y+1] != 'X' && d[v.x][v.y] + 1 < d[v.x][v.y+1]){
			d[v.x][v.y+1] = d[v.x][v.y] + 1;
			que.push(v + CPoint(0, 1));
		}
		if(v.y-1 >= 0 && field[v.x][v.y-1] != 'X' && d[v.x][v.y] + 1 < d[v.x][v.y-1]){
			d[v.x][v.y-1] = d[v.x][v.y] + 1;
			que.push(v + CPoint(0, -1));
		}
		if(v.x+1 < H  && field[v.x+1][v.y] != 'X' && d[v.x][v.y] + 1 < d[v.x+1][v.y]){
			d[v.x+1][v.y] = d[v.x][v.y] + 1;
			que.push(v + CPoint(1, 0));
		}
		if(v.x-1 >= 0 && field[v.x-1][v.y] != 'X' && d[v.x][v.y] + 1 < d[v.x-1][v.y]){
			d[v.x-1][v.y] = d[v.x][v.y] + 1;
			que.push((v + CPoint(-1, 0)));
		}
	}
	return d[goal.x][goal.y];
}

bool CPoint::operator==(const CPoint& obj)
{
	return (x == obj.x && y == obj.y);
}

bool CPoint::operator!=(const CPoint& obj)
{
	return !(*this == obj);
}

CPoint CPoint::operator+(const CPoint& obj)
{
	CPoint tmp;
	tmp.x = x + obj.x;
	tmp.y = y + obj.y;
	return tmp;
}

C++: #include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<cctype>
#include<iostream>

#define N 1010

int n,m,w;
const int dx[]={0,1,0,-1};
const int dy[]={1,0,-1,0};
char a[N][N];
int d[N][N];
int f[N][2];

int Bfs(int,int,int,int);

int main(){
#ifndef ONLINE_JUDGE
	freopen("2.txt","r",stdin);
#endif
	int ans=0;
	scanf("%d%d%d",&n,&m,&w);
	for(int i=1;i<=n;i++){
		for(int j=1;j<=m;j++){
			std::cin>>a[i][j];
			if(a[i][j]=='S')
				f[0][0]=i,f[0][1]=j;
			else if(isdigit(a[i][j]))
				f[a[i][j]-'0'][0]=i,f[a[i][j]-'0'][1]=j;
		}
	}
	for(int i=1;i<=w;i++)
		ans+=Bfs(f[i-1][0],f[i-1][1],f[i][0],f[i][1]);
	printf("%d\n",ans);
	return 0;
}

int Bfs(int bx,int by,int ex,int ey){
	memset(d,0,sizeof d);
	std::queue<std::pair<int,int> >q;
	q.push(std::make_pair(bx,by));
	d[bx][by]=1;
	while(q.size()){
		int x=q.front().first;
		int y=q.front().second;
		q.pop();
		if(x==ex && y==ey)
			break;
		for(int i=0;i<4;i++){
			int fx=x+dx[i];
			int fy=y+dy[i];
			if(fx<1 || fx>n || fy<1 || fy>m || d[fx][fy] || a[fx][fy]=='X')
				continue;
			d[fx][fy]=d[x][y]+1;
			q.push(std::make_pair(fx,fy));
		}
	}
	return d[ex][ey]-1;
}

C++: #include <bits/stdc++.h>

using namespace std;
typedef long long int ll;
typedef pair<int, int> P;
typedef pair<ll, ll> Pll;
typedef vector<int> Vi;
typedef tuple<int, int, int> T;
#define FOR(i,s,x) for(int i=s;i<(int)(x);i++)
#define REP(i,x) FOR(i,0,x)
#define ALL(c) c.begin(), c.end()
#define DUMP( x ) cerr << #x << " = " << ( x ) << endl

const int INF = 1<<29;
const int dr[4] = {-1, 0, 1, 0};
const int dc[4] = {0, 1, 0, -1};

int H, W, N;
string town[1024];
int dist[10][1024][1024];

inline bool in(int r, int c) {
  return 0 <= r && r < H && 0 <= c && c < W;
}

int main() {
  // use scanf in CodeForces!
  cin.tie(0);
  ios_base::sync_with_stdio(false);

  cin >> H >> W >> N;
  REP(i, H) cin >> town[i];
  int sr = 0, sc = 0;
  REP(i, H) REP(j, W) {
    if (town[i][j] == 'S') {
      sr = i, sc = j;
      break;
    }
  }

  int ans = 0;
  REP(i, N) {
    queue<T> que;
    que.push(T(sr, sc, 1));
    while (!que.empty()) {
      int r, c, d;
      tie(r, c, d) = que.front(); que.pop();
      if (dist[i][r][c]) continue;
      dist[i][r][c] = d;
      if (town[r][c] != 'S' && town[r][c] != '.' && town[r][c] != 'X' && town[r][c] - '0' == i+1) {
	ans += d-1;
	sr = r, sc = c;
	break;
      }
      REP(j, 4) {
	int nr = r + dr[j], nc = c + dc[j];
	if (in(nr, nc) && town[nr][nc] != 'X' && !dist[i][nr][nc]) {
	  que.push(T(nr, nc, d+1));
	}
      }
    }
  }

  cout << ans << endl;      
  return 0;
}

C++: #include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <queue>
#include <utility>

using namespace std;

char map[1005][1005];
int d[1005][1005];
int cx[12], cy[12];
int W, H, N;

typedef pair<int, int> P;

void solve(int x0, int y0, int hard, int* res) {
	queue<P> q;
	q.push(P(x0, y0));
	d[x0][y0] = 0;
	while (!q.empty()) {
		P pp = q.front(); q.pop();
		int x = pp.first, y = pp.second;
		int dx[4] = {0, -1, 0, 1};
		int dy[4] = {1, 0, -1, 0};
		int i;
		for (i = 0; i < 4; i++) {
			int nx = x + dx[i];
			int ny = y + dy[i];
			if (nx >= 0 && nx < H && ny >= 0 && ny < W 
				&& map[nx][ny] != 'X' && d[nx][ny] == 0 
				&& !(nx == x0 && ny == y0)) {
				d[nx][ny] = d[x][y] + 1;
				if (nx == cx[hard] && ny == cy[hard]) {
					*res += d[nx][ny];
					return;
				}
				q.push(P(nx, ny));
			}
		}
	}
}

int main() {
	while (scanf("%d%d%d", &H, &W, &N) == 3) {
		getchar();
		int i, j;
		for (i = 0; i < H; i++) {
			for (j = 0; j < W; j++) {
				scanf("%c", &map[i][j]);
				if (map[i][j] >= '1' && map[i][j] <= '9') {
					cx[map[i][j] - '0'] = i;
					cy[map[i][j] - '0'] = j;
					map[i][j] = '.';
				}
				else if (map[i][j] == 'S') {
					cx[0] = i, cy[0] = j;
					map[i][j] = '.';
				}
			}
			getchar();
		}
		int res = 0;
		for (i = 0; i < N; i++) {
			memset(d, 0, sizeof(d));
			solve(cx[i], cy[i], i+1, &res);
		}
		cout << res << endl;
	}
	return 0;
}