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 <numeric>
#include <string>

//ios::sync_with_stdio(false);

using namespace std;

const int INF = (1<<30) - 1;

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

int bfs(vector<string>& field, pair<int, int> start, pair<int, int> end){
    int H = field.size();
    int W = field[0].size();
    vector<vector<int> > d(H, vector<int>(W, INF));
    queue<pair<int, int> > nodes;
    
    d[start.first][start.second] = 0;
    nodes.push(start);
    
    while(!nodes.empty()){
        auto node = nodes.front(); nodes.pop();
        for(int i=0; i<4; i++){
            int nh = dh[i] + node.first;
            int nw = dw[i] + node.second;
            
            if(0<=nh&&nh<H && 0<=nw&&nw<W && field[nh][nw] != 'X' && d[nh][nw] == INF){
                d[nh][nw] = d[node.first][node.second] + 1;
                
                if(nh == end.first && nw == end.second)
                    return d[nh][nw];
                
                nodes.push(make_pair(nh, nw));
            }
        }
    }
    return -1;
}

int main(){
    int H, W, N;
    cin >> H >> W >> N;
    
    vector<string> field(H);
    for(int i=0; i<H; i++)
        cin >> field[i];
    
    vector<pair<int, int> > cheeses(N+1);
    
    for(int i=0; i<H; i++){
        for(int j=0; j<W; j++){
            char& c = field[i][j];
            if(c == 'S'){
                cheeses[0] = make_pair(i, j);
            }else if(c != '.' && c != 'X'){
                cheeses[c-'0'] = make_pair(i, j);
            }
        }
    }
    
    
    int ans = 0;
    for(int i=0; i<N; i++){
        ans += bfs(field, cheeses[i], cheeses[i+1]);
    }
    
	return 0;
}

C++: #include <bits/stdc++.h>
using namespace std;
const int MOD = 1e9 + 7;
typedef long long lint;
const int INF = 1e7;
#define rep(i, n) for (int i = 0; i < (n); ++i)
#define trep(i, k, n) for (int i = (k); i < (int)(n); ++i)
typedef pair<int, int> P;
#define H 1001
#define W 1001
int h, w;
int sx, sy;
int gx, gy;
char c[H][W];
int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, 1, -1};
int n;
vector<vector<int> > d(H, vector<int>(W, INF));
int bfs(void)
{
    rep(i, h)
    {
        rep(j, w)
        {
            d[i][j] = INF;
        }
    }
    queue<P> q;
    q.push(P(sy, sx));
    d[sy][sx] = 0;
    while (q.size())
    {
        P p = q.front();
        q.pop();
        rep(i, 4)
        {
            int ny = p.first + dy[i];
            int nx = p.second + dx[i];
            if (0 <= ny && ny < h && 0 <= nx && nx < w && c[ny][nx] != 'X' && d[ny][nx] == INF)
            {
                q.push(P(ny, nx));
                d[ny][nx] = d[p.first][p.second] + 1;
            }
        }
    }
    return d[gy][gx];
}
int main()
{
    cin >> h >> w >> n;
    rep(i, h)
    {
        rep(j, w)
        {
            cin >> c[i][j];
            if (c[i][j] == 'S')
            {
                sy = i;
                sx = j;
            }
        }
    }
    int ans = 0;
    trep(i, 1, n + 1)
    {
        rep(j, h)
        {
            rep(k, w)
            {
                if (c[j][k] == (i + '0'))
                {
                    gy = j;
                    gx = k;
                }
            }
        }
        ans += bfs();
        sy = gy;
        sx = gx;
    }
    cout << ans << endl;
    return 0;
}

C++: #include <string>
#include <vector>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <map>
#include <list>
#include <set>
#include <numeric>
#include <queue>
#include <stack>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <cstring>
using namespace std;
typedef long long LL;
typedef pair<int,int> P;
typedef pair<P, int> T;
char table[1000][1000];
char done[1000][1000];
int H,W,N;
vector<P> cur;
vector<P> nex;
T search(T s, char goal)
{
	cur.clear();
	int dist=s.second;
	cur.push_back(s.first);
	int dx[4]={-1,0,0,1};
	int dy[4]={0,-1,1,0};
	while(true){
		nex.clear();
		dist++;
		for(int i=0;i<cur.size();i++){
			int x=cur[i].first;
			int y=cur[i].second;
			for(int j=0;j<4;j++){
				int xx=x+dx[j];
				int yy=y+dy[j];
				if(0<=xx&&xx<H&&
				   0<=yy&&yy<W&&
				   done[xx][yy]!=goal){
					done[xx][yy]=goal;
					if(table[xx][yy]=='X')
					{
					}
					else if(table[xx][yy]==goal){
						return T(P(xx,yy), dist);
					}
					else
					{
						nex.push_back(P(xx,yy));
					}
				}
			}
		}
		nex.swap(cur);
	}
}
int main() {
	cur.reserve(1000*1000);
	nex.reserve(1000*1000);
	//cin >> H >> W >> N;
	scanf("%d %d %d", &H, &W, &N);
	T s;
	for(int i=0;i<H;i++){
		scanf("%s", table[i]);
		for(int j=0;j<W;j++){
			if(table[i][j]=='S'){
				s=T(P(i,j),0);
			}
		}
	}
	for(int i=0;i<N;i++){
		s=search(s,'0'+i+1);
	}
	printf("%d\n", s.second);
}