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

// typedef
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<string> VS;
typedef pair<int, int> PII;
typedef long long LL;

//container util
#define ALL(a)  (a).begin(),(a).end()
#define RALL(a) (a).rbegin(), (a).rend()
#define PB push_back
#define MP make_pair
#define SZ(a) int((a).size())
#define EACH(i,c) for(typeof((c).begin()) i=(c).begin(); i!=(c).end(); ++i)
#define EXIST(s,e) ((s).find(e)!=(s).end())
#define SORT(c) sort((c).begin(),(c).end())
//repetition
//------------------------------------------
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n)  FOR(i,0,n)


int dr[] = {1, -1, 0, 0};
int dc[] = {0, 0, 1, -1};

int bfs(vector<string>& map, PII start, PII goal) {
    int res = 0;
    VVI costs(map.size(), VI(map[0].size(), -1));
    costs[start.first][start.second] = 0;
    queue<PII> q;
    q.push(start);
    int cost = 0;
    while (!q.empty()) {
        PII p = q.front(); q.pop();
        if (p == goal) {
            cost = costs[p.first][p.second];
            break;
        }
        for (int i = 0; i < 4; i++) {
            int nr = p.first + dr[i];
            int nc = p.second + dc[i];
            if (nr >= 0 && nr < map.size() && nc >= 0 && nc < map[nr].size()
                    && map[nr][nc] != 'X' && costs[nr][nc] == -1) {
                costs[nr][nc] = costs[p.first][p.second] + 1;
                q.push(PII(nr, nc));
            }
        }
    }
    /*
    REP(i, costs.size()) {
        REP(j, costs[i].size()) {
            if (
            cerr << (costs[i][j] == -1 ? '?' : costs[i][j]) << " "; 
        }
        cerr << endl;
    }
    */
    return cost;
}

int getCost(vector<string>& map, int next) {
    char from = 'S';
    if (next > 1) from = char(next - 1 + '0');
    char to = char(next + '0');

    PII start, goal;
    for (int i = 0; i < map.size(); i++) {
        for(int j = 0; j < map[i].size(); j++) {
            if (map[i][j] == from) start = PII(i, j);
            if (map[i][j] == to) goal = PII(i, j);
        }
    }
    return bfs(map, start, goal);
}

int solve(vector<string>& map, int N) {
    int cost = 0;
    for (int i = 1; i <= N; i++) {
        cost += getCost(map, i);
    }
    return cost;
}

int main() {
    int H, W, N;
    cin >> H >> W >> N;
    vector<string> map;
    for (int i = 0; i < H; i++) {
        string s; cin >> s;
        map.push_back(s);
    }
    int answer = solve(map, N);
    cout << answer << endl;
}

C++: #include <iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<string>
#include<cstdlib>
#include<stack>
#include<queue>
#include <map>
#include<cmath>
#include<vector>
#define MAX_N 1000000
#define INF 0x3f3f3f3f
#define SIZE 1000
using namespace std;



struct note
{
    int x, y;
}start, ende;
typedef pair<int, int> P;
int H, W, N;
char a[1003][1003];
int sum;
int d[1003][1003];
int dx[4] = {0, 1, 0, -1};
int dy[4] = {1, 0, -1, 0};
void bfs(note h, note m)
{
    memset(d, -1, sizeof(d));
    queue<P> que;
    que.push(P(h.x, h.y));
    d[h.x][h.y] = 0;
    while (!que.empty())
    {
        P p = que.front();
        que.pop();
        for (int i = 0; i < 4; i++)
        {
            int xx = p.first + dx[i];
            int yy = p.second + dy[i];
            if (xx >= 0 && xx < H && yy >= 0 && yy < W && a[xx][yy] != 'X' && d[xx][yy] == -1)
            {
                d[xx][yy] = d[p.first][p.second] + 1;
                que.push(P(xx, yy));
            }
        }
    }
    sum += d[m.x][m.y];
    start = ende;
}
void solve()
{
    for (int i = 0; i < H; i++)
    {
        for (int j = 0; j < W; j++)
        {
            if (a[i][j] == 'S')
            {
                start.x = i;
                start.y = j;
                i = H;
                j = W;
            }
        }
    }
    for (int k = 0; k < N; k++)
    {
        for (int i = 0; i < H; i++)
        {
            for (int j = 0; j < W; j++)
            {
                if (a[i][j] == k + 49)
                {
                    ende.x = i;
                    ende.y = j;
                    bfs(start, ende);
                    i = H;
                    j = W;
                }
            }
        }
    }
    cout << sum << endl;
}
int main()
{
    cin >> H >> W >> N;
    for (int i = 0; i < H; i++)
    {
        cin >> a[i];
    }
    sum = 0;
    solve();
    return 0;
}

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

using namespace std;

int H, W, N;
char mapT[1000][1000];
char temp_map[1000][1000];

int temp_x = 0, temp_y;
char temp;
int min_rou = 0;
int min_route = 500000;
int final_min_route = 0;
vector<pair<int, int> > dir;

void findSmallRoute(int x, int y, char &factory) {
	if (mapT[x][y] == factory) {
		++min_rou;
		if (min_route > (min_rou-1)) {
			min_route = min_rou - 1;
			temp_x = x;
			temp_y = y;
		}
		--min_rou;
		return;
	}
	if (x < 0 || y >= W || x >= H || y < 0 || mapT[x][y] == 'X') {
		return;
	}
	++min_rou;
	mapT[x][y] = 'X';
	for (vector<pair<int, int> >::iterator it = dir.begin(); it != dir.end(); ++it) {
		findSmallRoute(x + it->first, y + it->second, factory);
		
	}
	mapT[x][y] = temp_map[x][y];
	--min_rou;
	return;
}

int main() {
	dir.push_back({ -1,0 });
	dir.push_back({ 0,1 });
	dir.push_back({ 1,0 });
	dir.push_back({ 0,-1 });
	int start_X = 0, start_Y = 0;
	cin >> H >> W >> N;
	for (int i = 0; i < H; i++) {
		for (int j = 0; j < W; ++j) {
			cin >> temp;
			mapT[i][j] = temp;
			if (temp == 'S') {
				start_X = i;
				start_Y = j;
			}
		}
	}

	for (int i = 0; i < H; ++i) {
		for (int j = 0; j < W; ++j) {
			temp_map[i][j] = mapT[i][j];
		}
	}
	start_X = 0;
	start_Y = 7;
	for (int factory = 1; factory != N + 1; ++factory) {
		
		char n = factory + '0';
		findSmallRoute(start_X, start_Y, n);
		for (int i = 0; i < H; ++i) {
			for (int j = 0; j < W; ++j) {
				mapT[i][j] = temp_map[i][j];
			}
		}
		final_min_route += min_route;
		min_rou = 0;
		min_route = 500000;
		
		start_X = temp_x;
		start_Y = temp_y;
	}

	cout << final_min_route << endl;
	//system("pause");
	return 0;
}