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 <bits/stdc++.h>

using namespace std;

#define LOG(...) fprintf(stderr,__VA_ARGS__)
//#define LOG(...)
#define FOR(i,a,b) for(int i=(int)(a);i<(int)(b);++i)
#define REP(i,n) for(int i=0;i<(int)(n);++i)
#define ALL(a) (a).begin(),(a).end()
#define RALL(a) (a).rbegin(),(a).rend()
#define EXIST(s,e) ((s).find(e)!=(s).end())
#define SORT(c) sort(ALL(c))
#define RSORT(c) sort(RALL(c))

typedef long long ll;
typedef unsigned long long ull;
typedef vector<bool> vb;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector<vb> vvb;
typedef vector<vi> vvi;
typedef vector<vll> vvll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;

char maze[1000][1000];
bool G[1000][1000];

const int dx[] = {-1,0,1,0}, dy[] = {0,1,0,-1};

int main() {
    int h, w, n;
    cin >> h >> w >> n;
    REP(y, h) REP(x, w) {
        cin >> maze[y][x];
    }
    vector<pii> cheese(n+1);
    REP(y, h) REP(x, w) {
        if (maze[y][x] == 'S') {
            cheese[0] = {x, y};
        } else if (isdigit(maze[y][x])) {
            cheese[maze[y][x] - '0'] = {x, y};
        }
    }
    int res = 0;
    REP(i, n) {
        fill_n((bool *)G, 1000*1000, false);
        pii sentinel = {-1, -1};
        pii goal = cheese[i+1];
        queue<pii> que;
        que.push(cheese[i]);
        que.push(sentinel);
        int cnt = 0;
        while (1) {
            pii p = que.front(); que.pop();
            if (p == sentinel) {
                if (que.empty()) break;
                que.push(sentinel);
                cnt++;
                continue;
            }
            if (p == goal) {
                break;
            }
            REP(i, 4) {
                int sx = p.first + dx[i], sy = p.second + dy[i];
                if (0 <= sx && sx < w && 0 <= sy && sy < h && maze[sy][sx] != 'X') {
                    if (!G[sy][sx]) {
                        G[sy][sx] = true;
                        que.push({sx, sy});
                    }
                }
            }
        }
        res += cnt;
    }
    cout << res << endl;
}

C++: #include<iostream>
#include<string>
#include<cstdio>
#include<algorithm>
#include<stack>
#include<queue>
#include<vector>
#include<cmath>
#include<utility>
#include<set>
#include<complex>
#include<map>
#define vi vector<int>
#define vvi vector<vector<int> >
#define ll long long int
#define vl vector<ll>
#define vvl vector<vector<ll>>
#define vb vector<bool>
#define vc vector<char>
#define vs vector<string>
#define ld long double
#define INF 1e9
#define EPS 0.0000000001
#define rep(i,n) for(int i=0;i<n;i++)
#define CC puts("-------ok--------");
#define all(in) in.begin(), in.end()
#define bv vector<bool>
using namespace std;
typedef pair<int, int> pii;
#define MAX 99999999
vector<vector<char> > v(100,vc(100));
vector<pii>u(1000);
int mx[]={0,0,1,-1};
int my[]={1,-1,0,0};
int h,w,n;
int bfs(pii st,pii g){
    queue<pii>que;
    vvi d(1000,vi(1000,INF));
    que.push(st);
    d[st.first][st.second]=0;
    while(!que.empty()){
        pii p=que.front(); que.pop();
        if(p==g)break;
        rep(i,4){
            int ny=p.first+my[i]; int nx=p.second+mx[i];
            pii np=pii(ny,nx);
            if(0<=ny&&ny<h&&0<=nx&&nx<w&&d[ny][nx]==INF&&v[ny][nx]!='X')
            {
                d[ny][nx]=d[p.first][p.second]+1;
                que.push(np);
            }
        }
    }
    return d[g.first][g.second];
}
int main(){
    pii st;
    cin>>h>>w>>n;
    int ans=0;
    rep(i,h)rep(j,w){
        cin>>v[i][j];
        if(v[i][j]=='S')st=pii(i,j);
            else if(v[i][j]!='X'&&v[i][j]!='.'){
            u[(v[i][j]-48)]=pii(i,j);
            //cout<<v[i][j]-48<<endl;
        }
    }
    u[0]=st;
    for(int i=0;i<n;i++){
        ans+=bfs(u[i],u[i+1]);
    }
    cout<<ans<<endl;
}

C++: #include "stdio.h"
#include "queue"
#include "utility"
using namespace std;
typedef pair<int, int>P;

queue<P>Q;
P now;
P goal[10];
int N;
int W;
int H;
char map[1000][1000] = {};
int x[4] = { 1,0,-1,0 };
int y[4] = { 0,1,0,-1 };
int dis[1000][1000] ;
int ans=0;
int box = 0;

int main() {
	scanf("%d %d %d", &H, &W, &N);
	for (int i = 0; i < H; i++) {
		scanf("%s", map[i]);
	}
	printf("\n");
	for (int i = 0; i < H; i++) {
		for (int j = 0; j < W; j++) {
			if (map[i][j] >= '1'&&map[i][j] <= '9') {
				goal[map[i][j] - '0'].first = i;
				goal[map[i][j] - '0'].second = j;
				map[i][j] = '.';
			}
			else if (map[i][j] == 'S') {
				now.first = i;
				now.second = j;
				map[i][j] = '.';
			}
		}
	}
	for (int i = 1; i <= N; i++) {
		Q.push(now);
		//printf("%d %d????????¢?´¢\n", now.first, now.second);
		box = 0;
		for (int j = 0; j < H; j++) {
			for (int k = 0; k < W; k++) {
				dis[j][k] = 10000000;
			}
		}
		dis[Q.front().first][Q.front().second] = 0;
		while (!Q.empty()) {
			for (int j = 0; j < 4; j++) {
				if (map[Q.front().first + y[j]][Q.front().second + x[j]] == '.') {
					if (dis[Q.front().first + y[j]][Q.front().second + x[j]] > dis[Q.front().first][Q.front().second] + 1) {
						now.first = Q.front().first + y[j];
						now.second = Q.front().second + x[j];
					//	dis[now.first][now.second] = dis[Q.front().first][Q.front().second] + 1;
						printf("%d %d??????%d %d????????£???\n", Q.front().first, Q.front().second, now.first, now.second);
						Q.push(now);
						if (now.first == goal[i].first&&now.second == goal[i].second) {
						//	printf("hijiki\n");
							box = dis[now.first][now.second];
							while (!Q.empty()) {
								Q.pop();
							}
							if (Q.empty())break;
						}
					}
				}
			}
			//printf("hijiki\n");
			if (!Q.empty()) {
				Q.pop();
			}
			//printf("hijiki\n");
		}
		//printf("hijiki\n");
		ans += box;
	}
	printf("%d", ans);
	return 0;
}