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++: //
//  main.cpp

#include <iostream>
#include <queue>
using namespace std;
using ll = long long;
int h,w,n;
bool matrix[1001][1001]={{}};
bool visited[1001][1001]={{}};
pair<int,int> target;
struct state{
	int x;
	int y;
	int depth;
};

ll min(ll x,ll y){
	if(x < y){
		return x;
	}else{
		return y;
	}
}

/*

ll dfs(ll depth,int x,int y){
	if(!matrix[x][y])return MAX;
	if(target.first == x && target.second == y)return depth;
	
	ll a,b,c,d;
	a = b = c = d = MAX;
	if(!visited[x+1][y]){
		visited[x+1][y] = true;
		a = dfs(depth+1,x+1,y);
		visited[x+1][y] = false;
	}
	if(!visited[x-1][y]){
		visited[x-1][y] = true;
		b = dfs(depth+1,x-1,y);
		visited[x-1][y] = false;
	}
	if(!visited[x][y+1]){
		visited[x][y+1] = true;
		c = dfs(depth+1,x,y+1);
		visited[x][y+1] = false;
	}
	if(!visited[x][y-1]){
		visited[x][y-1] = true;
		d = dfs(depth+1,x,y-1);
		visited[x][y-1] = false;
	}
	return min(a,min(b,min(c,d)));
}
*/
ll bfs(int x,int y){
	queue<state> willvisit;
	willvisit.push({x,y,0});
	ll ret;
	while(1){
		state now = willvisit.front();
		willvisit.pop();
		
		if(now.x == target.first && now.y == target.second){
			ret = now.depth;
			break;
		}
		
		if(!visited[now.x+1][now.y]){
			if(matrix[now.x+1][now.y]){
				visited[now.x+1][now.y] = true;
				willvisit.push({now.x+1,now.y,now.depth+1});
			}
		}
		if(!visited[now.x-1][now.y]){
			if(matrix[now.x-1][now.y]){
				visited[now.x-1][now.y] = true;
				willvisit.push({now.x-1,now.y,now.depth+1});
			}
		}
		if(!visited[now.x][now.y+1]){
			if(matrix[now.x][now.y+1]){
				visited[now.x][now.y+1] = true;
				willvisit.push({now.x,now.y+1,now.depth+1});
			}
		}
		if(!visited[now.x][now.y-1]){
			if(matrix[now.x][now.y-1]){
				visited[now.x][now.y-1] = true;
				willvisit.push({now.x,now.y-1,now.depth+1});
			}
		}
	}
	
	return ret;
}

void visitedReset(){
	for(int i=0;i<1001;i++){
		for(int j=0;j<1001;j++){
			visited[i][j] = false;
		}
	}
}

int main(){
	for(int i=0;i<1001;i++){
		for(int j=0;j<1001;j++){
			matrix[i][j] = visited[i][j] = false;
		}
	}
	
	cin >> h >> w >> n;
	pair<int,int> cheese[10];
	for(int i=1;i<=h;i++){
		for(int j=1;j<=w;j++){
			char input;
			cin >> input;
			switch(input){
				case '.':
					matrix[i][j] = true;
					break;
				case 'X':
					matrix[i][j] = false;
					break;
				case 'S':
					matrix[i][j] = true;
					cheese[0] = make_pair(i,j);
					break;
				default:
					matrix[i][j] = true;
					cheese[input - '0'] = make_pair(i,j);
					break;
			}
		}
	}
	
	ll answer=0;
	for(int i=0;i<n;i++){
		target = cheese[i+1];
		visited[cheese[i].first][cheese[i].second] = true;
		
		answer += bfs(cheese[i].first,cheese[i].second);
		visitedReset();
	}
	/*
	for(int i=0;i<n;i++){
		target = cheese[i+1];
		visited[cheese[i].first][cheese[i].second] = true;
		answer += dfs(0,cheese[i].first,cheese[i].second);
		visited[cheese[i].first][cheese[i].second] = false;
	}
	*/
	cout << answer << endl;
	return 0;
}

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

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

int H, W;
char 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 time;

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 (muscle-1 == 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;
                time += 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();
}

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

const int MAX_SIZE = 1000;
char field[MAX_SIZE + 1][MAX_SIZE + 1];

const int STEP_NUM = 4;
const int STEP[STEP_NUM][STEP_NUM] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};

using Position = std::pair<int,int>;

const int MAXN = 10;
Position locations[MAXN];
 
int H, W, N;

int get_shortest_distance(int current_HP)
{
	int sx = locations[current_HP-1].first;
	int sy = locations[current_HP-1].second;
	int ex = locations[current_HP].first;
	int ey = locations[current_HP].second;

	bool is_visit[MAX_SIZE + 1][MAX_SIZE + 1]={};
	is_visit[sx][sy]=true;

	std::vector<Position> frontier;
	frontier.push_back(Position{sx,sy});
	for(int step=0;step<W*H;step++)
	{
		std::vector<Position> next_frontier;
		for(auto p:frontier)
			for(int i=0;i<STEP_NUM;i++)
			{
				int nx = p.first+STEP[i][0];
				int ny = p.second+STEP[i][1];
				if(nx==ex && ny==ey)	return step+1;
				if(nx<0 || H<=nx) 		continue;
				if(ny<0 || W<=ny) 		continue;
				if(field[nx][ny]=='X') 	continue;
				if(is_visit[nx][ny]) 	continue;
				next_frontier.push_back(std::make_pair(nx,ny));
				is_visit[nx][ny] = true;
			}
		frontier = next_frontier;
	}
	return -1;
}

int solve()
{
	int total_step = 0;
	for(int i=1;i<N+1;i++)
		total_step += get_shortest_distance(i);
	return total_step;
}

int main()
{
	scanf("%d %d %d", &H, &W, &N);
	for(int i=0; i<H; i++)
		scanf("%s", field[i]);
	for(int i=0; i<H; i++)
		for(int j=0; j<W; j++)
		{
			if(field[i][j]=='S')
				locations[0] = std::make_pair(i,j);
			if(isdigit(field[i][j]))
				locations[field[i][j]-'0'] = std::make_pair(i,j);
		}
	printf("%d\n", solve());
	return 0;
}