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<algorithm>
#include<vector>
#include<queue>
#include<deque>
#include<map>
#include<set>
#include<string>
#include<sstream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<cctype>
#include<climits>
using namespace std;
#define REP(i, j) for(int i = 0; i < j; i++)
#define FOR(i, j, k) for(int i = j; i < k; i++)
#define P pair<int, int>
const int INF = INT_MAX / 2;

int h, w, n;

bool CanMove(int y, int x, vector< vector<char> > m){
    if(y < 0) return false;
    if(x < 0) return false;
    if(y >= h) return false;
    if(x >= w) return false;
    if(m[y][x] == 'X') return false;
    return true;
}

class C{
    public:
    int y, x, step;
    C(int _y, int _x, int _step);
    bool operator>(const C &c) const{
        return step > c.step;
    }
};

C::C(int _y, int _x, int _step){
    y = _y;
    x = _x;
    step = _step;
}

int bfs(int gy, int gx, int y, int x, vector< vector<char> > m){
    priority_queue<C, vector<C>, greater<C> > open;
    open.push( C(y, x, 0) );
    vector< vector<int> > closed(m.size(), vector<int>(m[0].size()));
    REP(i, m.size()) REP(j, m[0].size()) closed[i][j] = INF;
    int my[] = {0, 0, 1, -1};
    int mx[] = {1, -1, 0, 0};
    int ret;

    while(!open.empty()){
        C now = open.top();
        open.pop();
        if(now.y == gy && now.x == gx){
            ret = now.step;
            break;
        }

        closed[now.y][now.x] = now.step;

        REP(i, 4){
            int ny = now.y + my[i], nx = now.x + mx[i];
            if(CanMove(ny, nx, m) && closed[ny][nx] > now.step + 1){
                open.push( C(ny, nx, now.step + 1) );
            }
        }
    }
    return ret;
}

int main(){
    cin >>h >>w >>n;
    vector< vector<char> > m(h, vector<char>(w) );
    vector<int> y(n + 2), x(n + 2);

    //start of input
    REP(i, h){
        REP(j, w){
            cin >>m[i][j];
            if(m[i][j] == 'S'){
                y[0] = i;
                x[0] = j;
            }
            if(m[i][j] - '0' > 0 && m[i][j] - '0' <= n){
                int num = m[i][j] - '0';
                y[num] = i;
                x[num] = j;
            }
        }
    }
    //end of input

    int ans = 0;
    REP(i, n){
        ans += bfs(y[i + 1], x[i + 1], y[i], x[i], m);
    }
    cout <<ans <<endl;
    return 0;
}

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

using namespace std;

int H, W, N;
char map[1024][1024];
int dist[1024][1024];
int factories[10];
int dx[4] = {0, 1, 0, -1};
int dy[4] = {-1, 0, 1, 0};

int bfs(int from, int to)
{
    queue<int> q;
    q.push(from);
    dist[from / W][from % W] = 0;
    int fx = to % W;
    int fy = to / W;
        
    while (!q.empty())
    {
        int x = q.front() % W;
        int y = q.front() / W;
        q.pop();
        if (x == fx && y == fy)
        {
            return dist[fy][fx];
        }
        for (int d = 0; d < 4; ++d)
        {
            int nx = x + dx[d];
            int ny = y + dy[d];
            if (0 <= nx && nx < W && 0 <= ny && ny < H &&
                map[ny][nx] != 'X' && dist[ny][nx] == -1)
            {
                q.push(ny * W + nx);
                dist[ny][nx] = dist[y][x] + 1;
            }
        }
    }
    
}

void solve()
{
    int result = 0;
    for (int i = 0; i < N; ++i)
    {
        memset(dist, -1, sizeof dist);
        result += bfs(factories[i], factories[i + 1]);
    }
    cout << result << endl;
}

int main()
{
    cin >> H >> W >> N;
    for (int h = 0; h < H; ++h)
    {
        for (int w = 0; w < W; ++w)
        {
            cin >> map[h][w];
            if (isdigit(map[h][w]))
            {
                factories[map[h][w] - '0'] = h * W + w;
            }
            if (map[h][w] == 'S')
            {
                factories[0] = h * W + w;
            }
        }
    }
	solve();
    return 0;
}

C++: #include<iostream>
#include<algorithm>
#include<stdio.h>
#include<queue>
using namespace std;

typedef pair<int, int> pi;
pair <int, int>p;
pair <int, int> po;
int n, m,c;
char ma[1001][1001];
int ix, iy,x,y;
int te[1001][1001];
int xw[4] = { 1, 0, -1, 0 };
int yw[4] = { 0, 1, 0, -1 };
char name[10] = { '1', '2', '3', '4', '5', '6', '7', '8', '9' };
int nat = 0;
int na;
int op = 10000;
int main()
{	queue<pi> q;
	cin >> n >> m >> na;
	for (int i = 0; i < n; i++){
		for (int i2 = 0; i2 < m; i2++){
			cin >> ma[i][i2];
			te[i][i2] = op;
			if (ma[i][i2] == 'S'){
				p.first = i;
				p.second = i2;
			}
		}
	}
	
	int count;

	count = 0;
	q.push(p);
	
	te[p.first][p.second] = 0;
	while (!q.empty()){
		p = q.front();
		po = p;
		q.pop();
		
		for (int i = 0; i < 4; i++){
			x = p.first + xw[i];
			y = p.second + yw[i];
			if (0<=x && x<n&&0<=y && y<m&&ma[x][y] != 'X'&&te[x][y] == op){

				if (ma[x][y] == name[nat]){
					po.first = x;
					po.second = y;
					while (!q.empty()){ q.pop(); }
					q.push(po);
					po = p;
					count += te[p.first][p.second] + 1;
					nat++; 
					if (nat == na){ cout << count << endl; return 0; }
					//memset(te, op, sizeof(te));
					for (int i2 = 0; i2 <= n; i2++){
						for (int i3 = 0; i3 <= m; i3++){
							te[i2][i3] = op;
						}
					}
					te[x][y] = 0;
					break;
				}

				else{
					po.first = x;
					po.second = y;
					q.push(po);
					po = p;
					te[x][y] = te[p.first][p.second] + 1;
				}
			}
		}
	}
}