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 <algorithm>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <iostream>
#include <ostream>
#include <queue>
#include <stack>
#include <string>
#include <vector>
#define INF 1000000000
#define rep(i,a,b) for (int i=(a);i<(b);i++)
#define rev(i,a,b) for (int i=(a)-1;i>=b;i--)
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef queue<int> qi;
typedef queue< pair<int, int> > qpii;
typedef vector<int> vi;
typedef vector<int, int> vii;
typedef vector<string> vs;
typedef vector< pair<int, int> > vpii;
int dx[4] = { 0, 1, 0, -1 };
int dy[4] = { 1, 0, -1, 0 };

char f[1001][1001];
int h,w,n;
int d[1001][1001];

int bfs(pii s) {
  qpii q;
  rep(i,0,h)
    rep(j,0,w)
      d[i][j] = INF;
  q.push(s);
  d[s.first][s.second] = 0;

  int num = 0, hp = 1;
  while(q.size()) {
    pii p = q.front();
    q.pop();

    if(atoi(&f[p.first][p.second]) == hp) {
      num += d[p.first][p.second];
      if(hp == n) break;
      while(q.size()) q.pop();
      rep(i,0,h)
        rep(j,0,w)
          d[i][j] = INF;
      d[p.first][p.second] = 0;
      hp++;
    }

    rep(i,0,4) {
      int my = p.first + dy[i];
      int mx = p.second + dx[i];
      if(0<=my&&my<h && 0<=mx&&mx<w && f[my][mx] != 'X' && d[my][mx] == INF) {
        q.push(pii(my, mx));
        d[my][mx] = d[p.first][p.second] + 1;
      }
    }
  }
  return num;
}

int main(){
	cin.tie(0);
	ios::sync_with_stdio(false);

  cin >> h >> w >> n;
  pii s;
  rep(i,0,h)
    rep(j,0,w) {
      cin >> f[i][j];
      if(f[i][j] == 'S') {
        s.first = i;
        s.second = j;
      }
    }

  cout << bfs(s) << endl;

	return 0;
}

C++: #include <stdio.h>
#include <queue>

#define MAP_SIZE_MAX 1001
#define INF 100000000

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

int get_distance(int sx, int sy, int goal,
                 int h, int w, char map[][MAP_SIZE_MAX],
                 int *gx, int *gy) {
  std::queue<point> queue;
  queue.push(point(sx, sy));

  // initalize distance array
  int distance[MAP_SIZE_MAX][MAP_SIZE_MAX];
  for (int i = 0; i < MAP_SIZE_MAX; i++) {
    for (int j = 0; j < MAP_SIZE_MAX; j++) {
      distance[i][j] = INF;
    }
  }
  distance[sx][sy] = 0;

  // ???????????¢?´¢
  while (true) {
    point current = queue.front();
    queue.pop();
    int x = current.first;
    int y = current.second;

    // goal!
    if (map[x][y] == goal + '0') {
      *gx = x;
      *gy = y;
      return distance[x][y];
    }

    // 4 ???????????????
    int d[] = { 0, 1, 0, -1, 0 };
    for (int i = 0; i < 4; i++) {
      int _x = x + d[i];
      int _y = y + d[i + 1];
      if (map[_x][_y] != 'X' &&
          distance[_x][_y] == INF &&
          0 <= _x && _x < h && 0 <= _y && _y < w) {
        distance[_x][_y] = distance[x][y] + 1;
        queue.push(point(_x, _y));
      }
    }
  }
}

int solve(int h, int w, int n, char map[][MAP_SIZE_MAX]) {
  // find start position
  int sx, sy, gx, gy;
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      if (map[i][j] == 'S') {
        sx = i;
        sy = j;
        break;
      }
    }
  }

  int result = 0;
  for (int i = 1; i <= n; i++) {
    result += get_distance(sx, sy, i, h, w, map, &gx, &gy);

    // ??´????????????????¬??????????????????????
    sx = gx;
    sy = gy;
  }

  return result;
}

int main() {
  int h, w, n;
  scanf("%d %d %d", &h, &w, &n);

  char map[MAP_SIZE_MAX][MAP_SIZE_MAX];
  for (int i = 0; i < h; i++) {
    scanf("%s", map[i]);
  }

  printf("%d\n", solve(h, w, n, map));

  return 0;
}

C++: #include "bits/stdc++.h"
#define MOD 1000000007
#define INF 11234567890
#define in std::cin
#define out std::cout
#define rep(i,N) for(LL i=0;i<N;++i)
typedef long long int LL;
typedef std::pair<LL, LL> P;
struct edge { LL to, cost; };

int H, W, N;
std::string field[1123];
int Sx, Sy, x[11], y[11], ans;

int d[1123][1123];
int dx[] = { 1,0,-1,0 }, dy[] = { 0,1,0,-1 };
void bfs(LL sx, LL sy, LL gx, LL gy)
{
	std::queue<P>que;
	memset(d, -1, sizeof(d));
	que.push({ sx,sy });
	d[sx][sy] = 0;
	while (que.size() > 0)
	{
		auto pos = que.front(); que.pop();
		if (pos.first == gx && pos.second == gy) { break; }
		rep(i, 4)
		{
			auto toX = pos.first + dx[i], toY = pos.second + dy[i];
			if (0 <= toX && toX < H && 0 <= toY && toY < W)
			{
				if (field[toX][toY] != 'X' && d[toX][toY] == -1)
				{
					que.push({ toX,toY });
					d[toX][toY] = d[pos.first][pos.second] + 1;
				}
			}
		}
	}
}

int main()
{
	in >> H >> W >> N;
	rep(i, H) { in >> field[i]; }

	rep(i, H)
	{
		rep(j, W)
		{
			if (field[i][j] == 'X') { continue; }
			if (field[i][j] == 'S') { Sx = i; Sy = j; }
			else if (field[i][j] != '.') { x[field[i][j] - '0'] = i; y[field[i][j] - '0'] = j; }
		}
	}
	x[0] = Sx; y[0] = Sy;
	rep(i, N)
	{
		bfs(x[i], y[i], x[i + 1], y[i + 1]);
		ans += d[x[i + 1]][y[i + 1]];
	}
	out << ans << std::endl;
	return 0;
}

C++: #define LOCAL

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>

#define SIZE 1010

using namespace std;

char map[SIZE][SIZE];
int dir[][2] = {0, 1, 0, -1, 1, 0, -1, 0};

int bfs(int &x, int &y, int h, int w, int target){
	int step[SIZE][SIZE];
	for(int i = 0; i < h; i++)
		fill(step[i], step[i] + w, -1);
	step[x][y] = 0;

	queue<pair<int, int> > q;
	q.push(make_pair(x, y));

	while(!q.empty()){
		pair<int, int> temp = q.front();
		q.pop();

		if(map[temp.first][temp.second] == target + '0'){
			x = temp.first;
			y = temp.second;
			return step[x][y];
		}

		for(int i = 0; i < 4; i++){
			int newx = temp.first + dir[i][0];
			int newy = temp.second + dir[i][1];

			if(0 <= newx && newx < h && 0 <= newy && newy < w
				&& step[newx][newy] == -1 
				&& map[newx][newy] != 'X'){
				q.push(make_pair(newx, newy));
				step[newx][newy] = step[temp.first][temp.second] + 1;
			}
		}
	}
}

int main(void){
#ifdef LOCAL
	freopen("data.in", "r", stdin);
#endif
	int n, w, h;
	int x, y;

	scanf("%d%d%d", &h, &w, &n);
	getchar();
	for(int i = 0; i < h; i++){
		for(int j = 0; j < w; j++){
			scanf("%c", &map[i][j]);

			if(map[i][j] == 'S'){
				x = i;
				y = j;
			}
		}
		getchar();
	}

	int result = 0;
	for(int i = 1; i <= n; i++)
		result += bfs(x, y, h, w, i);

	printf("%d\n", result);

	return 0;
}