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 <unordered_map>
#include <utility>
#include <array>
#include <cstring>

bool isObstacle[1000][1000];
bool done[1000][1000];

int main() {
	int h, w, n;
	std::cin >> h >> w >> n;

	std::unordered_map<int, int> factories;

	for (int i = 0; i < h; ++i) {
		for (int j = 0; j < w; ++j) {
			char c;
			std::cin >> c;

			if (c == 'S')
				factories[0] = j * 1000 + i;
			else if ('1' <= c && c <= '9')
				factories[c - '0'] = j * 1000 + i;
			else if (c == 'X')
				isObstacle[j][i] = true;
		}
	}

	int ans = 0;
	for (int i = 0; i < n; ++i) {
		const int sx = factories[i] / 1000, sy = factories[i] % 1000;
		const int gx = factories[i + 1] / 1000, gy = factories[i + 1] % 1000;

		std::memset(done, 0, sizeof(done));

		done[sx][sy] = true;

		auto candidate = [h, w](int x, int y) {
			std::array<int, 4> arr;
			arr[0] = ((x == 0 || isObstacle[x - 1][y] || done[x - 1][y]) ? -1 : (done[x - 1][y] = true, (x - 1) * 1000 + y));
			arr[1] = ((x == w - 1 || isObstacle[x + 1][y] || done[x + 1][y]) ? -1 : (done[x + 1][y] = true, (x + 1) * 1000 + y));
			arr[2] = ((y == 0 || isObstacle[x][y - 1] || done[x][y - 1]) ? -1 : (done[x][y - 1] = true, x * 1000 + y - 1));
			arr[3] = ((y == h - 1 || isObstacle[x][y + 1] || done[x][y + 1]) ? -1 : (done[x][y + 1] = true, x * 1000 + y + 1));

			return std::move(arr);
		};

		std::queue<std::pair<int, int>> q;
		q.push({ factories[i], 0 });
		while (!q.empty()) {
			const auto& top = q.front();
			const int nx = top.first / 1000, ny = top.first % 1000;
			int cost = top.second;

			auto&& c = candidate(nx, ny);
			for (auto v : c) {
				if (v != -1) {
					if (v / 1000 == gx && v % 1000 == gy) {
						ans += cost + 1;
						q.pop();
						goto end;
					}
					q.push({ v, cost + 1 });
				}
			}

			q.pop();
		}
	end:;
	}

	std::cout << ans << std::endl;
}

C++: #include <bits/stdc++.h>
using namespace std;
enum class Walked { wa, un };
struct P {
public:
    int x, y;
    P(int x, int y) : x(x), y(y) {};
    P(): x(0), y(0) {};
};
int dx[4] = { 0, 0, 1, -1 };
int dy[4] = { 1, -1, 0, 0 };

void solve() {
    int H, W, N;
    cin >> H >> W >> N;

    vector<string> town(H);
    P start_p;
    for (int i = 0; i < H; ++i) {
        cin >> town[i];
        for (int j = 0; j < W; ++j) {
            if (town[i][j] == 'S') {
                start_p = P(j, i);
            }
        }
    }
    int hp = 1;
    vector<bool> ate(N, false);
    int ans = 0;
    for (int i = 0; i < N; ++i) {
        vector<vector<Walked>> walked(H, vector<Walked>(W, Walked::un));
        vector<vector<int>> dis(H, vector<int>(W, INT_MAX));
        dis[start_p.y][start_p.x] = 0;
        queue<P> q;
        q.push(start_p);
        while(!q.empty()) {
            P po = q.front();
            q.pop();
            if (walked[po.y][po.x] == Walked::wa) continue;
            if (town[po.y][po.x] == 'X') continue;
            walked[po.y][po.x] = Walked::wa;
            int d = dis[po.y][po.x];
            int g_n = town[po.y][po.x] - '0';
            if (1 <= g_n && g_n <= 9 &&  g_n <= hp && !ate[g_n - 1]) {
                ans += d;
                start_p = po;
                hp += 1;
                ate[g_n - 1] = true;
                break;
            }
            for (int i = 0; i < 4; ++i) {
                int nx = po.x + dx[i];
                int ny = po.y + dy[i];
                if (nx < 0 || W <= nx || ny < 0 || H <= ny) continue;
                dis[ny][nx] = d + 1;
                q.push(P(nx, ny));
            }
        }
    }

    cout << ans << endl;

}

int main() {
    solve();
    return 0;
}

C++: #include<iostream>
#include<string>
#include<cstring>
#include<cmath>
#include<vector>
#include<sstream>
#include<cstdio>
#include<cstdlib>
#include<set>
#include<map>
#include<stack>
#include<queue>
#include<climits>
#include<algorithm>
#include<functional>
#include<iomanip>
#define LL long long
using namespace std;

int n,m,sum,cheese[15][2],sx,sy,gx,gy,book[1010][1010],dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
char a[1010][1010];

struct node{
    int x,y,step;
}t1,t2;

queue<struct node> q;

bool judge(int x,int y){
    if(x>=0 && x<n && y>=0 && y<m && !book[x][y] && a[x][y]!='X') return true;
    return false;
}

int bfs(void){
    if(sx==gx && sy==gy) return 0;
    while(!q.empty()) q.pop();
    t1.x=sx;
    t1.y=sy;
    t1.step=0;
    book[sx][sy]=1;
    q.push(t1);
    while(!q.empty()){
        t1=q.front();
        q.pop();
        t2.step=t1.step+1;
        int i;
        for(i=0;i<4;i++){
            t2.x=t1.x+dir[i][0];
            t2.y=t1.y+dir[i][1];
            if(t2.x==gx && t2.y==gy) return t2.step;
            if(judge(t2.x,t2.y)){
                    book[t2.x][t2.y]=1;
                    q.push(t2);
            }
        }
    }
}

int main(void){
    scanf("%d %d %d",&n,&m,&sum);
    int i,j;
    for(i=0;i<n;i++) scanf("%s",a[i]);
    for(i=0;i<n;i++){
        for(j=0;j<m;j++){
            if(a[i][j]=='S'){
                cheese[0][0]=i;
                cheese[0][1]=j;
            }
            if(a[i][j]>='1' && a[i][j]<='9'){
                cheese[a[i][j]-'0'][0]=i;
                cheese[a[i][j]-'0'][1]=j;
            }
        }
    }
    int ans=0;
    for(i=0;i<sum;i++){
        memset(book,0,sizeof(book));
        sx=cheese[i][0];sy=cheese[i][1];
        gx=cheese[i+1][0];gy=cheese[i+1][1];
        ans+=bfs();
    }
    printf("%d\n",ans);
    return 0;
}