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<cstdio>
#include<cstring>
#include<queue>
#include<vector>
#include<algorithm>
#include<cmath>
using namespace std;

int n,m,l,cnt,mx,my;
char a[1009][1009];
int vis[1009][1009];
pair<int,int> p[10],st;
int mov[4][2] = {1,0,0,-1,-1,0,0,1};
struct status
{
    int x,y;
    int ord;
    int fx;
    status(int a=0,int b=0,int c=0,int s=0)
    {
        x = a, y = b, ord = c, fx = s;
    }
    bool operator < (struct status t) const
    {
        if(ord != t.ord) return ord > t.ord;
        else return fx > t.fx;
    }
}tt[4];

void bfs(int x,int y,int color)
{
    queue <struct status> q;
    struct status temp(x,y,0,fabs(x-p[color].first) + fabs(y - p[color].second));
    q.push(temp);
    int flag = 0;
    while(!q.empty())
    {
        struct status nw = q.front();
        q.pop();
        if(nw.x == p[color].first && nw.y == p[color].second)
        {
            cnt += nw.ord;
            break;
        }
        vis[nw.x][nw.y] = 1;
        for(int i=0;i<4;i++)
        {
            int tx = mov[i][0] + nw.x, ty = nw.y + mov[i][1];
            if(tx>=0 && tx< n && ty>=0 && ty< m && !vis[tx][ty] && a[tx][ty] != 'X')
            {
                struct status tmp(tx,ty,nw.ord+1,fabs(tx-p[color].first) + fabs(ty - p[color].second));
                tt[i] = tmp;
                vis[tx][ty] = 1;
            }
        }
        sort(tt,tt+4);
        for(int i=0;i<4;i++) q.push(tt[i]);
    }
}

int main()
{
    while(~scanf("%d%d%d",&n,&m,&l))
    {
        getchar();
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<m;j++)
            {
                scanf("%c",&a[i][j]);
                if(a[i][j]>='0' && a[i][j]<='9')
                    p[a[i][j]-'0'].first = i, p[a[i][j]-'0'].second = j;
                if(a[i][j] == 'S') st.first = i, st.second = j;
            }
            getchar();
        }

        int sx = st.first, sy = st.second;
        cnt = 0;
        for(int i=1;i<=l;i++)
        {
            memset(vis,0,sizeof(vis));
            bfs(sx,sy,i);
            sx = p[i].first, sy = p[i].second;
        }
        printf("%d\n",cnt);
    }
    return 0;
}

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 <cstdio>
#include <algorithm>
#include <queue>
using namespace std;
/*(^(^(^(^(^o^)^)^)^)^) &#9602;&#9605;&#9607;&#9608;&#9619;&#9618;&#9617;('ω')&#9617;&#9618;&#9619;&#9608;&#9607;&#9605;&#9602; 初のBFS*/
typedef pair<int,int> p;
char x[1001][1001];
int c[10]={},d[10],y[1001][1001],a[10],b[10];
int h,q,n,i,j,now=1,sum=0,pro[10];
int bfs(){
	int dx[]={1,0,-1,0};
	int dy[]={0,1,0,-1};
	queue<p>orz;
	for(i=1;i<=h;i++){
	for(j=1;j<=q;j++){
		y[i][j]=10000000;
		if(x[i][j]=='S'){
			a[0]=i;
			b[0]=j;
			y[i][j]=0;
		}
		if(x[i][j]-'0'>0 && x[i][j]-'0'<10){
			a[x[i][j]-'0']=i;
			b[x[i][j]-'0']=j;
		}}}
	for(int u=1;u<=n;u++){
		while(orz.size()){
			orz.pop();
		}
	for(i=1;i<=h;i++){
	for(j=1;j<=q;j++){
		y[i][j]=10000000;
		}}
	while(1){
		orz.push(p(a[u-1],b[u-1]));
		p w=orz.front();
		orz.pop();
		if(w.first==a[u]&&w.second==b[u]){
			pro[u]=y[a[u]][b[u]]-10000000;
			break;
		}
		for(i=0;i<4;i++){
			int ax=w.first+dx[i];
			int ay=w.second+dy[i];
			if(ax>=1&&ax<=h&&ay>=1&&ay<=q&&y[ax][ay]==10000000&&x[ax][ay]!='X'){
				orz.push(p(ax,ay));
				y[ax][ay]=y[w.first][w.second]+1;
			}
		}
	}
	}
for(i=1;i<=n;i++){
		sum+=pro[i];
	}
return sum;
}
int main(){
scanf("%d %d %d",&h,&q,&n);
for(i=1;i<=h;i++){
scanf("%s",&x[i]);
}
for(i=1;i<=h;i++){
for(j=q-1;j>=0;j--){
	x[i][j+1]=x[i][j];
}}
int ans=bfs();
printf("%d\n",ans);
return 0;
}