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 "bits/stdc++.h"

using namespace std;

//#define int long long

#define FOR(i, a, b) for (int i = (a); i < (b); i++)
#define REP(i, n) for (int i = 0; i < (n); i++)

#define pb push_back
#define VDEL(v, n) v.erase(v.begin() + (n))
#define ALL(v) v.begin(), v.end()

#define INTMAX 2147483647
#define INF 200000000
#define TINT(str) atoi(str.c_str())
#define TSTR(num) to_string(num)

typedef long long ll;
typedef pair<int, int> PII;
typedef vector<int> VI;
typedef vector<vector<int>> VII;

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

PII goal[10];
char k[1000][1000];
int fx, fy;
int H,W;

int BFS(int x, int y)
{
    VII cost;
    cost = VII(H, VI(W, INT_MAX));

    cost[fx][fy] = 0;

    queue<PII> q;

    q.push(make_pair(fx, fy));

    while(!q.empty())
    {
        PII now = q.front();
        q.pop();
        int nx = now.first;
        int ny = now.second; 

        if(nx == x && ny == y)
        {
            return cost[nx][ny];
        }

        REP(i, 4)
        {
            if(nx + dx[i] >= H ||
            nx + dx[i] < 0) continue;
            if(ny + dy[i] >= W || 
            ny + dy[i] < 0) continue;

            if(k[nx + dx[i]][ny + dy[i]] != 'X')
            {
                if(cost[nx + dx[i]][ny + dy[i]] > 
                cost[nx][ny])
                {
                    cost[nx + dx[i]][ny + dy[i]] =
                        cost[nx][ny] + 1;
                    q.push(make_pair(nx + dx[i], ny + dy[i]));
                }
            }
        }
    }

    return -1;
}

signed main()
{
    int N;
    cin >> H >> W >> N;

    char str[1001];
    REP(h, H)
    {
        scanf("%s", str);
        REP(w, W)
        {
            k[h][w] = str[w];
            if(k[h][w] == 'S')
            {
                fx = h;
                fy = w;
            }
            if(k[h][w] != '.' &&
                k[h][w] != 'X')
            {
                goal[k[h][w] - '1'] = make_pair(h, w);
            }
        }
    }
    int ans = 0;

    REP(i, N)
    {
        ans += BFS(goal[i].first, goal[i].second);
        fx = goal[i].first;
        fy = goal[i].second;
    }

    cout << ans << endl;

    return 0;
}

C++: #include<iostream>
#include<queue>
#include<utility>
#define INF 5000000
using namespace std;

char fl[1010][1010];

int bfs(int sx, int sy, int gx, int gy, int mx, int my) {
	typedef pair<int, int>P;
	int d[1010][1010];
	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, h,w);
	}
	cout << al << endl;
	return 0;
}

C++: #include<iostream>
#include<vector>
#include<algorithm>

using namespace std;

const int MAX = 1001;
const int INF = (1<<20);
typedef pair<int,int> P;
typedef pair<int,P> PP;

int dx[4] = {1,-1,0,0};
int dy[4] = {0,0,1,-1};
char grid[MAX][MAX];
int cost[MAX][MAX];
int H,W,N;
vector<PP> V;

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

}

void input(){
  for(int i = 1; i <= H; i++)
    for(int j = 1; j <= W; j++){
      cin >> grid[i][j];
      PP pp;

      if(grid[i][j] == 'S' || '0' <= grid[i][j] && grid[i][j] <= '9'){
	if(grid[i][j] == 'S') pp.first = 0;
	else pp.first = grid[i][j] - '0';
	
	pp.second = P(i,j);
	V.push_back(pp);
      }
    }
}


bool isIn(P p){
  return 0 < p.first && p.first<= H && 0 < p.second && p.second <= W;
}
void solve(P p){

  int n = cost[p.first][p.second];

  for(int i = 0; i < 4; i++){
    P next = p;
    next.first += dy[i];
    next.second += dx[i];
    if(grid[next.first][next.second] != 'X' && cost[next.first][next.second] > n+1 && isIn(next)){
	cost[next.first][next.second] = n+1;
	solve(next);
    }
  }
}

P find(int n){
  for(int i = 0; i < V.size(); i++)
    if(V[i].first == n) return V[i].second;

}

int main(){

  cin >> H >> W >> N;

  input();
  sort(V.begin(),V.end());
  
  int ans = 0;
 
  for(int i = 1; i <= N; i++){
    init();
    P f = find(i-1), t = find(i);
    cost[f.first][f.second] = 0;
    solve(f);
    ans += cost[t.first][t.second];
    
  }
  cout << ans << endl;
  return 0;
}