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>
#include <tuple>
#include <string.h>

#define BLOCK -1
#define ROAD 0
#define GONE -2

void clear(std::queue<std::tuple<int, int, int, int*>> &q) {
	while (!q.empty()) {
		auto& item = q.front();
		auto& map = std::get<int*>(item);
		delete[] map;
		q.pop();
	}
}

int* copy(int* base, int size) {
	int* copied = new int[size];
	std::memcpy(copied, base, size);
	return copied;
}

int main() {
	int w, h, total;
	std::cin >> h >> w >> total;
	int* original = new int[w * h];
	char temp;
	int positionW = -1, positionH = -1;

	for (int i = 0; i < w * h; i++) {
		std::cin >> temp;
		if (temp == 'S') {
			positionW = i % w;
			positionH = i / w;
			original[i] = ROAD;
		}
		else if (temp == '.') {
			original[i] = ROAD;
		}
		else if (temp == 'X') {
			original[i] = BLOCK;
		}
		else {
			original[i] = temp - '0';
		}
	}

	int* first = new int[w * h];
	std::memcpy(first, original, sizeof(int) * w * h);

	int next = 1;
	std::queue<std::tuple<int, int, int, int*>> queue;
	queue.push(std::make_tuple(positionW, positionH, 0, first));

	while (queue.size() != 0) {
		auto item = queue.front();
		queue.pop();

		int posW = std::get<0>(item);
		int posH = std::get<1>(item);
		int step = std::get<2>(item);
		int* map = std::get<3>(item);

		if (posW < 0 || posW >= w || posH < 0 || posH >= h)
			continue;

		int current = map[posH * w + posW];
		if (current == BLOCK || current == GONE) {
			delete[] map;
			continue;
		}

		map[posH * w + posW] = GONE;

		if (current > 0 && current == next) {
			next++;
			clear(queue);
			// if finished
			if (next > total) {
				std::cout << step << std::endl;
				return 0;
			}
			std::memcpy(map, original, sizeof(int) * w * h);
			map[posH * w + posW] = GONE;
		}

		step++;
		queue.push(std::make_tuple(posW + 1, posH, step, copy(map, sizeof(int) * w * h)));
		queue.push(std::make_tuple(posW - 1, posH, step, copy(map, sizeof(int) * w * h)));
		queue.push(std::make_tuple(posW, posH + 1, step, copy(map, sizeof(int) * w * h)));
		queue.push(std::make_tuple(posW, posH - 1, step, copy(map, sizeof(int) * w * h)));
		delete[] map;
	}
	return 0;
}

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

typedef pair<int, int> Pair;
const int INF = 100000000;

int H, W, N;
const int MAX_H = 1000, MAX_W = 1000;
char plant[MAX_H][MAX_W];
int sx, sy;
int dx[4] = {0,1,0,-1}, dy[4] = {1,0,-1,0};
int d[MAX_H][MAX_W];
int mytime;

void bfs() {
    queue<Pair> que;
    for (int i = 0; i < H; i++) {
        for (int j = 0; j < W; j++) {
            d[i][j] = INF;
        }
    }
    char muscle = '1';
    que.push(Pair(sx,sy));
    d[sx][sy] = 0;
    while (que.size()) {
        Pair p  = que.front(); que.pop();
        if (int(muscle)-49 == N) break;
        for (int i = 0; i < 4; i++) {
            int nx = p.first + dx[i], ny = p.second + dy[i];
            if (0 <= nx && nx < H && 0 <= ny && ny < W && plant[nx][ny] != 'X' && d[nx][ny] == INF) {
                que.push(Pair(nx, ny));
                d[nx][ny] = d[p.first][p.second] + 1;
            }
            if (muscle == plant[nx][ny]) {
                while(que.size()) {que.pop();}
                que.push(Pair(nx, ny));
                muscle = muscle + 1;
                mytime += d[nx][ny];
                for (int i = 0; i < H; i++) {
                    for (int j = 0; j < W; j++) {
                        d[i][j] = INF;
                    }
                }
                d[nx][ny] = 0;
                break;
            }
        }
    }
}

// void solve() {
//     time = 0;
//     bfs();
//     cout << time << endl;
// }

// int main () {
//     cin >> H >> W >> N;
//     for (int i = 0; i < H; i++) {
//         for (int j = 0; j < W; j++) {
//             cin >> plant[i][j];
//             if(plant[i][j] == 'S') {sx = i; sy = j;}
//         }
//     }
//     solve();
// }

void solve() {
    mytime = 0;
    bfs();
    printf("%d\n",mytime);
}

int main () {
    scanf("%d%d%d",&H,&W,&N);
    for (int i = 0; i < H; i++) {
        scanf("%s", plant[i]);
        for (int j = 0; j < W; j++) {
            if(plant[i][j] == 'S') {sx = i; sy = j;}
        }
    }
    solve();
}

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


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

#define HMAX 1000
#define WMAX 1000
#define NMAX 9
#define INF 10000000
#define EMPTY -1
#define OBSTACLE -2

int H, W, N;
int map[HMAX + 2][WMAX + 2];

int dirs_h[] = {0, 0, 1, -1};
int dirs_w[] = {1, -1, 0, 0};

struct Position {
	int h;
	int w;
};
Position factory[NMAX + 1];
Position dirs[4] = {
	Position{ 0,  1},
	Position{ 0, -1},
	Position{ 1,  0},
	Position{-1,  0}
};

using namespace std;

int go(Position start, Position end) {
	queue<Position> q;
	q.push(start);

	map[start.h][start.w] = 0;
	int min = 0;
	while (!q.empty()) {
		Position pos = q.front();

		q.pop();
		
		rep(i, 4){
			Position pos_n = Position{pos.h + dirs[i].h, pos.w + dirs[i].w};

			if (map[pos_n.h][pos_n.w] != OBSTACLE) {
				if (map[pos_n.h][pos_n.w] == EMPTY) {
					q.push(pos_n);
				}else{
					if (min > map[pos_n.h][pos_n.w] + 1)
						min = map[pos_n.h][pos_n.w] + 1;
				}
			}
		}
		map[pos.h][pos.w] = min;
		min = INF;
		if (pos.h == end.h && pos.w == end.w)
			break;
	}
	int ans = map[end.h][end.w];

	rep(i, H + 2){
		rep(j, W + 2){
			/*debug
			switch(map[i][j]){
				case OBSTACLE:
					cout << "  X";
				break;
				case EMPTY:
					cout << "   ";
				break;
				default:
					cout << setw(3) << map[i][j];
				break;
			}*/
			
			map[i][j] = map[i][j] >= 0 ? EMPTY : map[i][j];
		}
		//cout << endl;
	}
	return ans;
}

int main() {
	scanf("%d%d%d", &H, &W, &N);
	
	rep(i, H){
		rep(j, W){
			char m;
			scanf(" %c",&m);
			int m_i = m - '0';
			switch (m) {
				case 'S':
					factory[0] = Position{i + 1, j + 1};
					map[i + 1][j + 1] = EMPTY;
				break;
				case 'X':
					map[i + 1][j + 1] = OBSTACLE;
				break;
				case '.':
					map[i + 1][j + 1] = EMPTY;
				break;
				default:
					int num = m - '0';
					factory[num] = Position{i + 1, j + 1};
					map[i + 1][j + 1] = EMPTY;
				break;
			}
		}
	}

	rep(i, H + 2){
		map[i][0] = OBSTACLE;
		map[i][W + 1] = OBSTACLE;
	}

	rep(j, W + 2){
		map[0][j] = OBSTACLE;
		map[H + 1][j] = OBSTACLE;
	}

	int sum = 0;
	rep(i, N)
		sum += go(factory[i], factory[i + 1]);

	cout << sum << endl;
}