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<cstdio>
#include<queue>

using namespace std;

#define REP(i,n) for(int i=0;i<(n);i++)
#define FOR(i,a,b) for(int i=(a);i<(b);i++)
#define INF 1e+8

struct P{
    int x;
    int y;
};

int w,h,n;
char feld[101][101];
int d[101][101];
int sx,sy,gx,gy;
int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};
int ans=0;
P che[15];


int bfs(){
    REP(i,n){
        P sp=che[i];
        sx=che[i].x;
        sy=che[i].y;
        gx=che[i+1].x;
        gy=che[i+1].y;
        queue<P> que;
        REP(y,h)REP(x,w)d[y][x]=INF;
        que.push(sp);
        d[sy][sx]=0;
        while(!que.empty()){
            P p=que.front();
            que.pop();
            int x=p.x;
            int y=p.y;
            if(x==gx&&y==gy){
                ans+=d[gy][gx];
                break;
            }
            REP(i,4){
                int nx=x+dx[i];
                int ny=y+dy[i];
                if(nx<0||ny<0&&nx>=w&&ny>=h)continue;
                if(feld[ny][nx]!='X'&&d[ny][nx]==INF){
                    P next;
                    next.x=nx;
                    next.y=ny;
                    que.push(next);
                    d[ny][nx]=d[y][x]+1;
                }
            }
        }
    }
    return 0;
}

int main(){
    cin>>h>>w>>n;
    REP(y,h){
        REP(x,w){
            scanf(" %c",&feld[y][x]);
            if(feld[y][x]=='S'){
                che[0].x=x;
                che[0].y=y;
            }else if(feld[y][x]>='1'&&feld[y][x]<='9'){
                char c=feld[y][x];
                che[c-'0'].x=x;
                che[c-'0'].y=y;
            }
        }
    }
    bfs();
    cout<<ans<<endl;
    return 0;
}

C++: #if 0
#cflags(-std=c++14 -Wall)
#endif
#include<iostream>
template<typename T>
T input(std::istream& os = std::cin){T t;os >> t;return t;}

#include<vector>
#include<string>
#include<queue>
#include<numeric>

struct pos{
  int x, y;
  template<typename T>
  auto&& operator[](T&& t)const{return std::forward<T>(t)[y][x];}
};
template<typename F>
struct itr{
  int r;
  std::pair<pos, int> t;
  F shortest;
  bool flag;
  itr& operator++(){++r;flag = true;return *this;}
  int& operator*(){if(flag)t = shortest(r, t.first.x, t.first.y), flag = false;return t.second;}
  bool operator==(const itr& other)const{return r == other.r;}
  bool operator!=(const itr& other)const{return !(*this == other);}
};
template<typename F>
itr<F> make_itr(const pos& p, F&& f){return ++itr<F>{0, {p, 0}, f};}
template<typename F>
itr<F> make_itr(int r, F&& f){return itr<F>{r, {}, f};}

int main(){
  const auto H = input<int>();
  const auto W = input<int>();
  const auto N = input<int>();
  const std::vector<std::string> data = [H]{
    std::vector<std::string> data;
    data.reserve(H);
    for(int i = 0; i < H; ++i)
      data.emplace_back(input<std::string>());
    return data;
  }();
  const pos po = [&]{
    pos po;
    for(int j = 0; j < H; ++j)
      for(int i = 0; i < W; ++i)
        if(data[j][i] == 'S')
          po = {i, j};
    return po;
  }();
  auto shortest = [&](int rank, int i, int j){
    std::vector<std::vector<char>> flags(H, std::vector<char>(W));
    std::queue<std::pair<pos, int>> q;
    q.push({{i, j}, 0});flags[j][i] = true;
    while(true){
      const auto& d = q.front();
      const auto& p = d.first;
      if(p[data] == rank+'0')
        return q.front();
      p[flags] = true;
      auto add = [&](const pos& po){
        if(!po[flags])
          if(po[data] != 'X')
            q.push({po, d.second+1}), po[flags] = true;
          else
            po[flags] = true;
      };
      for(int a = -1; a <= 1; a += 2)
        if(0 <= p.x + a && p.x + a < W)
          add(pos{p.x+a, p.y});
      for(int b = -1; b <= 1; b += 2)
        if(0 <= p.y + b && p.y + b < H)
          add(pos{p.x, p.y+b});
      q.pop();
    }
    return q.front();
  };
  std::cout << std::accumulate(make_itr(po, shortest), make_itr(N+1, shortest), 0) << std::endl;
}

C++: #include "bits/stdc++.h"
#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[11230];
LL Sx, Sy, xy[110];
LL ans;

LL d[11234560];
std::vector<edge>G[11234560];
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()
{
	in >> H >> W >> N;
	rep(i, H) { in >> field[i]; }

	rep(x, H)
	{
		rep(y, W)
		{
			if (field[x][y] == 'X') { continue; }
			if (field[x][y] == 'S') { Sx = x; Sy = y; }
			if (field[x][y] != '.') { xy[field[x][y] - '0'] = x*W + y; }
			if (x > 0)
			{
				if (field[x - 1][y] != 'X')
				{
					G[x*W + y].push_back({ (x - 1)*W + y,1 });
					G[(x - 1)*W + y].push_back({ x*W + y,1 });
				}
			}
			if (y > 0)
			{
				if (field[x][y - 1] != 'X')
				{
					G[x*W + y].push_back({ x*W + (y - 1),1 });
					G[x*W + (y - 1)].push_back({ x*W + y,1 });
				}
			}
			if (x < H - 1)
			{
				if (field[x + 1][y] != 'X')
				{
					G[x*W + y].push_back({ (x + 1)*W + y,1 });
					G[(x + 1)*W + y].push_back({ x*W + y,1 });
				}
			}
			if (y < W - 1)
			{
				if (field[x][y + 1] != 'X')
				{
					G[x*W + y].push_back({ x*W + (y + 1),1 });
					G[x*W + (y + 1)].push_back({ x*W + y,1 });
				}
			}
		}
	}
	dijkstra(Sx*W + Sy);
	rep(i, N)
	{
		ans += d[xy[i + 1]];
		dijkstra(xy[i + 1]);
	}

	out << ans << std::endl;
	return 0;
}