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

int main()
{
	queue < pair<int, int> > q;
	pair<int, int> p;

	char **m;
	char c[10] = { "123456789" };
	int **f;
	int n, k, i, i1, c1, i2, sum = 0;

	cin >> n;
	cin >> k;
	cin >> c1;

	m = new char *[n + 2];
	f = new int *[n + 2];

	for (i = 0; i < n + 2; i++){
		m[i] = new char[k + 2];
		f[i] = new int[k + 2];
	}

	for (i = 1; i <= n; i++){
		for (i1 = 1; i1 <= k; i1++){
			cin >> m[i][i1];
		}
	}

	for (i = 0; i < n + 2; i++){
		for (i1 = 0; i1 < k + 2; i1++){
			if (i == 0 || i == n + 1){
				m[i][i1] = 'X';
			}
			else if (i1 == 0 || i1 == k + 1){
				m[i][i1] = 'X';
			}
		}
	}

	for (i = 1; i <= n; i++){
		for (i1 = 1; m[i][i1] != '\0'; i1++){
			if (m[i][i1] == 'S'){
				q.push(make_pair(i, i1));
			}
		}
	}



	pair<int, int> temp;

	temp = q.front();

	for (i = 0; i < c1; i++){

		for (i1 = 0; i1 < n + 2; i1++){
			for (i2 = 0; i2 < k + 2; i2++){
				if (i1 == 0 || i1 == n + 1){
					f[i1][i2] = 1;
				}
				else if (i2 == 0 || i2 == k + 1){
					f[i1][i2] = 1;
				}
				else
					f[i1][i2] = -1;
			}
		}

		f[temp.first][temp.second] = 0;

		while (!q.empty()){
			p = q.front();
			q.pop();

			//上への探索
			if (m[p.first - 1][p.second] != 'X' && f[p.first - 1][p.second] == -1){
				q.push(make_pair(p.first - 1, p.second));
				f[p.first - 1][p.second] = f[p.first][p.second] + 1;
			}

			//下への探索
			if (m[p.first + 1][p.second] != 'X' && f[p.first + 1][p.second] == -1){
				q.push(make_pair(p.first + 1, p.second));
				f[p.first + 1][p.second] = f[p.first][p.second] + 1;
			}

			//左への探索
			if (m[p.first][p.second - 1] != 'X' && f[p.first][p.second - 1] == -1){
				q.push(make_pair(p.first, p.second - 1));
				f[p.first][p.second - 1] = f[p.first][p.second] + 1;
			}

			//右への探索
			if (m[p.first][p.second + 1] != 'X' && f[p.first][p.second + 1] == -1){
				q.push(make_pair(p.first, p.second + 1));
				f[p.first][p.second + 1] = f[p.first][p.second] + 1;
			}

			//ゴールかどうか？
			if ( m[p.first][p.second] == c[i]){
				sum += f[p.first][p.second];
				temp = p;
			}

		}
	}
	
	cout << sum << endl;
	
return 0;
}

C++: #include <stdio.h>
#include <vector>
#include <queue>
#include <algorithm>
#define INF 1e8
using namespace std;

//firstにh、secondにwを入れる
typedef pair<int, int> PII;

//S、1...Nまでの座標を格納する
PII cheese[10];

const int MAX_H = 1010, MAX_W = 1010;
int H, W, N;
char field[MAX_H][MAX_W];
int d[MAX_H][MAX_W];

int dh[] = {1, 0, -1, 0};
int dw[] = {0, 1, 0, -1};

bool infield(int h, int w){
    return (0<=h && h<H && 0<=w && w<W);
}

//sからgまでの最短手数を返す
int bfs(PII s, PII g){
    queue<PII> que;
    //init
    for(int i=0; i<H; i++){
        for(int j=0; j<W; j++)
            d[i][j] = INF;
    }
    //fill(d, d+sizeof(d), INF);
    que.push(s);
    d[s.first][s.second] = 0;
    
    while(!que.empty()){
        PII p = que.front(); que.pop();
        if(p == g)
            break;
        for(int i=0; i<4; i++){
            int nh = p.first+dh[i];
            int nw = p.second+dw[i];
            
            if(infield(nh, nw) && field[nh][nw]!='X' && d[nh][nw]==INF){
                que.push(PII(nh, nw));
                d[nh][nw] = d[p.first][p.second] + 1;
            }
        }
    }
    
    return d[g.first][g.second];
}

void solve(){
    int ans = 0;
    
    //cheeseリストを作る
    for(int i=0; i<H; i++){
        for(int j=0; j<W; j++){
            if(field[i][j] == 'S')
                cheese[0] = PII(i, j);
            
            for(char c='1'; c<='9'; c++){
                if(field[i][j] == c)
                    cheese[c-'0'] = PII(i, j);
            }
        }
    }
    for(int i=0; i<N; i++)
        ans += bfs(cheese[i], cheese[i+1]);
    printf("%d\n", ans);
}

int main(){
    scanf("%d%d%d", &H, &W, &N);
    for(int i=0; i<H; i++)
        scanf("%s", field[i]);
    solve();
    return 0;
}

C++: //include
//------------------------------------------
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <ctime>
#include <climits>
#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)

//constant
//--------------------------------------------
const double EPS = 1e-10;
const double PI  = acos(-1.0);

struct Edge{
  int to, cost;

  Edge(int t, int c): to(t), cost(c)
  {}
  bool operator>(const Edge& rhs) const{
	return cost > rhs.cost;
  }
};
typedef vector< vector<Edge> > Graph;

void Dijkstra(const Graph& edges, vector<int>& d, int s){
  const int V = edges.size();
  priority_queue<PII, vector<PII>, greater<PII> > pq;
  fill(d.begin(), d.end(), 123456789);
  d[s] = 0;
  pq.push(MP(0,s));

  while(!pq.empty()){
	PII pii = pq.top(); pq.pop();
	int v = pii.second;
	if(d[v] < pii.first) continue;
	for(int i=0;i<edges[v].size();++i){
	  const Edge& e = edges[v][i];
	  if(d[e.to] > d[v] + e.cost){
		d[e.to] = d[v] + e.cost;
		pq.push(MP(d[e.to], e.to));
	  }
	}
  }
}

int dx[] = {-1,0,1,0};
int dy[] = {0,-1,0,1};
int main(){
  int H, W, N; cin >> H >> W >> N;
  cin.ignore();
  vector<string> vs(H);
  REP(i,H) getline(cin, vs[i]);
  Graph G(H*W);
  vector<int> p(N+1);
  REP(y,H) REP(x,W){
	int id_f = y*W + x;
	if(vs[y][x] == 'X') continue;
	if(vs[y][x] == 'S') p[0] = id_f;
	if('1' <= vs[y][x] && vs[y][x] <= '9')
	  p[vs[y][x]-'0'] = id_f;
	
	REP(i,4){
	  int tx = x + dx[i], ty = y + dy[i];
	  int id_t = ty*W + tx;
	  if(tx < 0 || W <= tx || ty < 0 || H <= ty) continue;
	  if(vs[ty][tx] != 'X')
		G[id_f].PB(Edge(id_t, 1));
	}
  }

  int ans = 0;
  VI dist(H*W);
  REP(i,N){
	Dijkstra(G, dist, p[i]);
	ans += dist[p[i+1]];
  }
  cout << ans << endl;
  
  return 0;
}