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;
typedef long long int ll;
typedef vector<int> VI;
typedef pair<int, int> PII;
typedef pair<int, pair<int,int>> tup;
#define ALL(a) (a).begin(), (a).end()
#define RALL(a) (a).rbegin(), (a).rend()

#define EACH(i, c) \
  for (typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define SORT(c) sort((c).begin(), (c).end())

#define FOR(i, a, b) for (int i = (a); i < (b); ++i)
#define REP(i, n) FOR(i, 0, n)
const double PI = acos(-1.0);
#define CLR(a) memset((a), 0, sizeof(a))

// int tansaku[110];
// map<string,string> d;
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};

int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);
  bool  visited[1010][1010];
  char field[1010][1010];
  queue<tup> kuwa;
  int H, W, N;
  CLR(visited);

  cin >> H >> W >> N;
  REP(j, H) {
    REP(i, W) { cin >> field[i][j]; }
  }
  tup start;
  cin.ignore();
  REP(i, W) {
    REP(j, H) {
      if (field[i][j] == 'S') {
        start = {0,{i, j}};
      }
    }
  }
  kuwa.push(start);
  int ans=0;
  int cost =0;
  char cheeze='1';
  while(!kuwa.empty()){
  	tup r = kuwa.front();kuwa.pop();
  	int haba = r.first;
  	PII p = r.second;
  	visited[p.first][p.second] = true;
  	if(field[p.first][p.second]==cheeze){
      cost += haba;
  		if(cheeze-'0' == N)break;
  		cheeze++;
  		queue<tup> daisuke;
  		swap(kuwa,daisuke);
  		kuwa.push(make_pair(0,p));
      CLR(visited);
  		continue;
  	}
  	for(int i=0 ; i<4 ;i++){
          PII new_xy = {p.first + dx[i], p.second + dy[i]};
          if(0 <= new_xy.first && new_xy.first < W &&
              0 <= new_xy.second && new_xy.second < H &&
                  !visited[new_xy.first][new_xy.second] &&
                  field[new_xy.first][new_xy.second] != 'X'){
          kuwa.push(make_pair(haba+1,new_xy));	
          }
        }
  }
  cout << cost << endl;
  return 0;
}

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

#define rep(i, n) REP(i, 0, n)
#define repr(i, n) for (int i = (n); i >= 0; i--)
#define ALL(v) v.begin(), v.end()
#define MSG(a) cout << #a << " " << a << endl;
#define REP(i, x, n) for (int i = x; i < n; i++)
#define OP(m) cout << m << endl
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;

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

int h, w, n;

char c[1001][1001];
int d[1001][1001];
int sx, sy;
int ans = 0;

void bfs()
{

    for (int i = 1; i <= n; i++)
    {
        rep(s, h) rep(t, w) d[s][t] = 0;
        queue<pii> q;
        q.push(pii(sx, sy));
        while (!q.empty())
        {
            pii p = q.front();
            q.pop();

            if (c[p.first][p.second] == (char)(i + '0'))
            {
                sx = p.first, sy = p.second;
                ans += d[sx][sy];
                break;
            }
            rep(j, 4)
            {
                int nx = p.first + dx[j], ny = p.second + dy[j];

                if (!(0 <= nx && nx < h && 0 <= ny && ny < w) || d[nx][ny] > 0)
                    continue;

                if (c[nx][ny] == 'X')
                    continue;

                q.push(pii(nx, ny));
                d[nx][ny] = d[p.first][p.second] + 1;
            }
        }
    }
}

int main()
{
    cin >> h >> w >> n;
    rep(i, h)
    {
        rep(j, w)
        {
            cin >> c[i][j];
            if (c[i][j] == 'S')
                sx = i, sy = j;
        }
    }
    bfs();
    OP(ans);

    return 0;
}

C++: #include<stdio.h>
#include<queue>
#define INF -1
using namespace std;
typedef pair<int, int>P;

char joi[1000][1001];
int h, w;
int sy, sx, gy, gx;
int d[1000][1000];

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

int solve(){
	queue<P>que;
	for (int i = 0; i < h; i++)
		for (int j = 0; j < w; j++)
			d[i][j] = INF;
	que.push(P(sy, sx));
	d[sy][sx] = 0;

	while (!que.empty()){
		P p = que.front(); que.pop();
		if (p.first == gy&&p.second == gx)break;
		for (int i = 0; i < 4; i++){
			int ny = p.first + dy[i]; int nx = p.second + dx[i];
			if (0 <= ny&&ny < h && 0 <= nx&&nx < w&&d[ny][nx] == INF&&joi[ny][nx] != 'X'){
				d[ny][nx] = d[p.first][p.second] + 1;
				que.push(P(ny, nx));
			}
		}
	}
	return d[gy][gx];
}
int main(){
	int n, cnt = 0;
	P q[9];
	scanf("%d%d%d", &h, &w, &n);
	for (int i = 0; i < h; i++){
		scanf("%s", joi[i]);
		for (int j = 0; j < w; j++){
			if ('0' < joi[i][j] && joi[i][j] <= '9')q[joi[i][j] - '1'] = P(i, j);
			if (joi[i][j] == 'S'){ sy = i; sx = j;}
		}
	}
	for (int i = 0; i < n; i++){
		gy = q[i].first; gx = q[i].second;
		cnt += solve();
		sy = gy; sx = gx;
	}
	printf("%d\n", cnt);
	return 0;
}

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

using namespace std;

typedef pair<int, int> P;

int h, w, n;
char field[1024][1024];

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

int bfs(char st, char en)
{
	static int minTime[1024][1024];
	queue<P> q;
	
	memset(minTime, -1, sizeof(minTime));
	for (int i = 0; i < h; i++){
		for (int j = 0; j < w; j++){
			if (field[i][j] == st){
				q.push(P(i, j));
				minTime[i][j] = 0;
			}
		}
	}
	
	for (; !q.empty(); q.pop()){
		P now = q.front();
		if (field[now.first][now.second] == en) return (minTime[now.first][now.second]);
		
		for (int i = 0; i < 4; i++){
			int ny = now.first + dy[i], nx = now.second + dx[i];
			if (0 <= ny && ny < h && 0 <= nx && nx < w && minTime[ny][nx] == -1 && field[ny][nx] != 'X'){
				minTime[ny][nx] = minTime[now.first][now.second] + 1;
				q.push(P(ny, nx));
			}
		}
	}
	return (-1);
}

int main()
{
	scanf("%d %d %d", &h, &w, &n);
	
	for (int i = 0; i < h; i++){
		scanf("%s", field[i]);
	}
	
	int cost = bfs('S', '1');
	
	for (int i = 1; i < n; i++){
		cost += bfs(i + '0', i + 1 + '0');
	}
	
	printf("%d\n", cost);
	
	return (0);
}