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 <algorithm>
#include <array>
#include <iostream>
#include <vector>
#include <limits>
#include <math.h>
#include <queue>
#include <tuple>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <memory>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <memory>

// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0558

using namespace std;

//// #define TEST
//
//#ifdef TEST
//static const string g_SAMPLE = R"(10 10 9
//.X...X.S.X
//6..5X..X1X
//...XXXX..X
//X..9X...X.
//8.X2X..X3X
//...XX.X4..
//XX....7X..
//X..X..XX..
//X...X.XX..
//..X.......)";
//static FILE* g_IN_FP;
//static const char* g_IN_FN = "./in.txt";
//#define scanf(...) fscanf(g_IN_FP, __VA_ARGS__)
//#endif // TEST

int main() {
//#ifdef TEST
//    g_IN_FP = fopen(g_IN_FN, "w");
//    fwrite(g_SAMPLE.c_str(), 1, g_SAMPLE.size(), g_IN_FP);
//    fclose(g_IN_FP);
//    g_IN_FP = fopen(g_IN_FN, "r");
//#endif // TEST
    int H, W, N;
    cin >> H >> W >> N;
    vector<vector<char>> field;
    field.reserve(H);
    for (int i = 0; i < H; i++) {
        field.push_back(vector<char>(W, '.'));
    }
    for (int i = 0; i < H; i++) {
        scanf("%s", &field[i][0]);
    }
    vector<pair<int,int>> factories(N+1, pair<int,int>(0,0));
    for (int i = 0; i < H; i++) {
        for (int j = 0; j < W; j++) {
            if (field[i][j] == 'S') {
                factories[0] = pair<int,int>(i,j);
            } else if ('1' <= field[i][j] && field[i][j] <= '0' + N) {
                factories[field[i][j] - '0'] = pair<int,int>(i,j);
            }
        }
    }
    function<int(pair<int,int>,pair<int,int>)> calcDist = [&field, H, W](pair<int,int> start, pair<int,int> end) -> int {
        vector<vector<int>> distMap;
        distMap.reserve(H);
        for (int i = 0; i < H; i++) {
            distMap.push_back(vector<int>(W, numeric_limits<int>::max()));
        }
        queue<pair<int,int>> seeds;
        seeds.push(start);
        distMap[start.first][start.second] = 0;
        while (true) {
//#ifdef TEST
//            for (int i = 0; i < H; i++) {
//                for (int j = 0; j < W; j++) {
//                    if (distMap[i][j] < numeric_limits<int>::max()) {
//                        cout << distMap[i][j];
//                    } else {
//                        cout << "@";
//                    }
//                }
//                cout << endl;
//            }
//            cout << endl;
//#endif // TEST
            pair<int,int> seed = seeds.front();
            seeds.pop();
            int dist = distMap[seed.first][seed.second];
            if (seed == end) {
                return dist;
            }
            using V = pair<int,int>;
            static const vector<V> VECTS = {V{-1,0}, V{1,0}, V{0,-1}, V{0,1}};
            for (V vec : VECTS) {
                V pt(seed.first + vec.first, seed.second + vec.second);
                if (pt.first < 0 || pt.first >= H || pt.second < 0 || pt.second >= W) {
                    continue;
                }
                if (distMap[pt.first][pt.second] != numeric_limits<int>::max()) {
                    continue;
                }
                if (field[pt.first][pt.second] == 'X') {
                    continue;
                }
                seeds.push(pt);
                distMap[pt.first][pt.second] = dist + 1;
            }
        }
        return numeric_limits<int>::max();
    };
    int total = 0;
    for (int i = 1; i <= N; i++) {
        total += calcDist(factories[i-1],factories[i]);
    }
    printf("%d\n",total);
    return 0;
}

C++: #include<iostream>
#include<cstring>
#include<queue>
using namespace std;
struct p{
	int x;
	int y;
	int cnt;
};

int maps[1000][1000]={};
char map[1000][1000]={};
bool mapb[1000][1000]={},used[1000][1000]={};

int main(){
	queue<p> m;
	p f;
	p v;
	int h,w,n,i,j,z,sp=1,mv[4][2]={{0,-1},{1,0},{0,1},{-1,0}},count=0;
	char u,math[10]="123456789";
	cin>>h>>w>>n;
	for(i=0;i<h;i++){
		for(j=0;j<w;j++){
			cin>>u;
			for(z=0;z<9;z++){
				if(u==math[z]){
					maps[i][j]=z+1;
					mapb[i][j]=true;
				}
			}
			map[i][j]=u;
			if(u=='S'){
				f.x=j;
				f.y=i;
				f.cnt=0;
				m.push(f);
			}
		}
	}
	while(1){
		f=m.front();
		m.pop();
		if(used[f.y][f.x]==true){
			continue;
		}
		else{
			used[f.y][f.x]=true;
		}
		if(mapb[f.y][f.x]==true&&maps[f.y][f.x]<=sp){
			mapb[f.y][f.x]=false;
			count++;
			sp++;
			memset(used,0,sizeof(used));
			while(!m.empty()){
				m.pop();
			}
			m.push(f);
			used[f.y][f.x]=true;
			if(count==n){
				break;
			}
		}
		for(i=0;i<4;i++){
			if(map[f.y+mv[i][1]][f.x+mv[i][0]]!='X'&&(f.x+mv[i][0])>=0&&(f.x+mv[i][0])<w&&(f.y+mv[i][1])>=0&&(f.y+mv[i][1])<h){
				v.x=f.x+mv[i][0];
				v.y=f.y+mv[i][1];
				v.cnt=f.cnt+1;
				m.push(v);
			}
		}
	}
	cout<<f.cnt<<endl;
	return 0;
}

C++: #include <iostream>
#include <queue>
#include <cstdio>
#include <cstring>

using namespace std;

int m, n, N, ans;
char mat[1000][1000];
int d[1000][1000], sx[10], sy[10];
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0, -1};

int bfs(int sx, int sy, int tx, int ty) {
    memset(d, -1, sizeof(d));
    d[sx][sy] = 0;
    queue<pair<int, int>> q;
    q.push(make_pair(sx, sy));
    int x, y, xx, yy;
    while (!q.empty()) {
        pair<int, int> cur = q.front(); q.pop();
        x = cur.first;
        y = cur.second;
        for (int i = 0; i < 4; i++) {
            xx = x + dx[i];
            yy = y + dy[i];
            if (xx >= 0 && xx < m && yy >= 0 && yy < n && mat[xx][yy] != 'X' && d[xx][yy] == -1) {
                d[xx][yy] = d[x][y] + 1;
                if (xx == tx && yy == ty) {
                    return d[xx][yy];
                }
                q.push(make_pair(xx, yy));
            }
        }
    }
    return 0;
}

void solve() {
    ans = 0;
    for (int i = 0; i < m; i++) {
        cin >> mat[i];
        for (int j = 0; j < n; j++) {
            if (mat[i][j] == 'S') {
                sx[0] = i;
                sy[0] = j;
            } else if (mat[i][j] >= '1' && mat[i][j] <= '9') {
                int t = mat[i][j] - '0';
                sx[t] = i;
                sy[t] = j;
            }
        }
    }
    for (int i = 1; i <= N; i++) {
        ans += bfs(sx[i-1], sy[i-1], sx[i], sy[i]);
    }
}

int main(int argc, const char * argv[]) {
    cin >> m >> n >> N;
    solve();
    cout << ans << endl;
    return 0;
}