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 <fstream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#include <stack>
#include <array>
#include <deque>
#include <algorithm>
#include <utility>
#include <cstdint>
#include <functional>
#include <iomanip>
#include <numeric>
#include <assert.h>
#include <bitset>
 
#define MOD 1000000007
#define INF 11234567890
#define in std::cin
#define out std::cout
#define rep(i,N) for(LL i=0;i<N;++i)
typedef long long int LL;
typedef std::pair<LL, LL> P;
struct edge { LL to, cost; };
 
LL H, W, N;
std::string field[1123];
LL Sx, Sy, xy[11];
LL ans;
 
LL d[1123456];
std::vector<edge>G[1123456];
void dijkstra(LL s)
{
    std::priority_queue<P, std::vector<P>, std::greater<P>>que;
    std::fill(d, d + H * W + 1, INF);
    d[s] = 0;
    que.push(P(0, s));
    while (!que.empty())
    {
        P p = que.top(); que.pop();
        LL v = p.second;
        if (d[v] < p.first) { continue; }
        rep(i, G[v].size())
        {
            edge e = G[v][i];
            if (d[e.to] > d[v] + e.cost)
            {
                d[e.to] = d[v] + e.cost;
                que.push(P(d[e.to], e.to));
            }
        }
    }
}
 
int main()
{
    try {
        in >> H >> W >> N;
        rep(i, H) { in >> field[i]; }
 
        rep(h, H)
        {
            rep(w, W)
            {
                if (field[h][w] == 'X') { continue; }
                if (field[h][w] == 'S') { Sx = h; Sy = w; }
                if (field[h][w] != '.') { xy[field[h][w] - '0'] = h*W + w; }
                if (h < H - 1)
                {
                    if (field[h + 1][w] != 'X')
                    {
                        G[h*W + w].push_back({ (h + 1)*W + w,1 });
                        G[(h + 1)*W + w].push_back({ h*W + w,1 });
                    }
                }
                if(false)if (w < W - 1)
                {
                    if (field[h][w + 1] != 'X')
                    {
                        G[h*W + w].push_back({ h*W + (w + 1),1 });
                        G[h*W + (w + 1)].push_back({ h*W + w,1 });
                    }
                }
            }
        }
        //dijkstra(Sx*W + Sy);
        //rep(i, N)
        //{
        //  ans += d[xy[i + 1]];
        //  dijkstra(xy[i + 1]);
        //}
 
        out << ans << std::endl;
        return 0;
    }
    catch (std::bad_alloc) { return 0; }
    catch (...) { return 0; }
}

C++: #include <iostream>
#include <string>
#include <cstring>
#include <fstream>
#include <random>
#include <cmath>
#include <iomanip>
#include <climits>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <map>
#include <deque>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <list>
#include <unordered_map>
#include <bitset>
#include <sstream>
#include <new>
#include <typeinfo>
#include <iterator>

typedef long long ll;
typedef unsigned long long ull;
constexpr ll mop = 1000000007;
constexpr ll mop2 = 998244353;

using namespace std;

struct Point {
	ll x, y;
	Point() {};
	Point(ll xx, ll yy):x(xx), y(yy){}
};
void initializeDis(vector<vector<ll>>& dis, ll& h, ll& w) {
	for (ll i = 0; i < h; i++) {
		for (ll j = 0; j < w; j++) {
			dis[i][j] = -1;
		}
	}
}

ll bfs(Point st, Point go, vector<vector<ll>>& dis, vector<vector<bool>>& grid, ll& h, ll& w) {
	queue<Point> Q;
	Q.push(st);
	dis[st.x][st.y] = 0;
	while (!Q.empty()) {
		Point now = Q.front();
		Q.pop();
		ll disnow = dis[now.x][now.y];
		Point tmp[4];
		for (ll i = 0; i < 4; i++) {
			tmp[i] = now;
		}
		tmp[0].x++;
		tmp[1].x--;
		tmp[2].y++;
		tmp[3].y--;
		for (ll i = 0; i < 4; i++) {
			if (0 <= tmp[i].x && tmp[i].x < h && 0 <= tmp[i].y && tmp[i].y < w && dis[tmp[i].x][tmp[i].y] == -1 && grid[tmp[i].x][tmp[i].y] == true) {
				dis[tmp[i].x][tmp[i].y] = disnow + 1;
				Q.push(tmp[i]);
			}
		}

	}
	/*for (ll i = 0; i < h; i++) {
		for (ll j = 0; j < w; j++) {
			cout << dis[i][j];
		}
		cout << endl;
	}*/
	return dis[go.x][go.y];
}

int main() {
	ll h, w, numCheese;
	cin >> h >> w >> numCheese;
	vector<vector<bool>> grid;
	grid.resize(h);
	vector<vector<ll>> dis;
	dis.resize(h);
	vector<Point> destinations;
	destinations.resize(numCheese + 1);
	for (ll i = 0; i < h; i++) {
		string str;
		cin >> str;
		grid[i].resize(w);
		dis[i].resize(w);
		for (ll j = 0; j < w; j++) {
			if (str[j] != 'X') {
				grid[i][j] = true;
				if (str[j] != '.') {
					if (str[j] == 'S') {
						destinations[0] = Point(i, j);
					}
					else {
						destinations[str[j] - '0'] = Point(i, j);
					}
				}
			}
			

		}
	}
	ll ans = 0;
	for (ll q = 0; q < numCheese; q++) {
		initializeDis(dis, h, w);
		Point st = destinations[q];
		Point go = destinations[q + 1];
		ans += bfs(st, go, dis, grid, h, w);
	}
	cout << ans << endl;
}

C++: #include <bits/stdc++.h>

using namespace std;

#define FOR(i,k,n) for(int i = (k); i < (n); i++)
#define REP(i,n) FOR(i,0,n)
#define INF 114514810
#define ELEM(array) (sizeof (array)/sizeof *(array))
#define MAX_N 100
#define SAFE_FREE(ptr) if( ptr != NULL ){ free(ptr); ptr = NULL; }
typedef unsigned int UINT;
typedef long long ll;
typedef queue<pair<int, int>> que;

char city[1005][1005];
int way[1005][1005];
int di[4] = { -1, 0, 0, 1 }; int dj[4] = { 0, -1, 1, 0 };

int main()
{
	int h, w, n;
	cin >> h >> w >> n;
	REP(i, h)REP(j, w)cin >> city[i][j];
	que start;
	REP(i, h)REP(j, w){
		if (city[i][j] == 'S')start.push(make_pair(i, j));
	}
	FOR(k, 1, n + 1)
	{
		REP(i, h)REP(j, w){
			if (city[i][j]-'0'==k )
			{
				start.push(make_pair(i, j));
			}
		}
	}
	int cnt = 0;

	REP(i, n)
	{
		REP(i, 1005)REP(j, 1005)way[i][j] = INF;
		que q;
		way[start.front().first][start.front().second] = 0;
		q.push(start.front());
		start.pop();
		while (1)
		{
			int tmpi = q.front().first; int tmpj = q.front().second;
			q.pop();
			if (tmpi == start.front().first&&tmpj == start.front().second)
			{
				cnt += way[tmpi][tmpj];
				break;
			}
			else
			{
				REP(i, 4){
					if (tmpi+di[i]>=0&&tmpi+di[i]<h&&tmpj+dj[i]>=0&&tmpj+dj[i]<w&&city[tmpi+di[i]][tmpj+dj[i]]!='X'&&way[tmpi+di[i]][tmpj+ dj[i]] == INF )
					{
						way[tmpi + di[i]][tmpj + dj[i]] = way[tmpi][tmpj] + 1;
						q.push(make_pair(tmpi + di[i], tmpj + dj[i]));
					}
				}
			}
			
		}
	}
	cout << cnt << endl;
	return 0;
}