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 <cstdio>
#include <cstdlib>
#include <iostream>
#include <string>
#include <cmath>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>

typedef long long ll;

using namespace std;

int mo[4]={0,1,0,-1};

int main(){
    int h,w,n,ans=0;
    bool fl[1000][1000]={0};
    char in[1000][1001];
    queue<pair<int,int> > qp;
    pair<int,int> p;
    
    scanf("%d%d%d",&h,&w,&n);
    
    for(int i=0;i<h;i++)
        scanf("%s",in[i]);
    
    for(int i=0;i<h;i++)
        for(int j=0;j<w;j++)
            if(in[i][j]=='S'){
                qp.push(make_pair(i,j));
                qp.push(make_pair(-5,-5));
                break;
            }
    
    for(int i=1;i<=n;i++){
        while(1){
            p=qp.front();
            qp.pop();
            if(p.first==-5 && p.second==-5){
                ans++;
                qp.push(make_pair(-5,-5));
                continue;
            }
            if(p.first<0 || h<=p.first || p.second<0 || w<=p.second || fl[p.first][p.second]) continue;
            if(in[p.first][p.second]=='0'+i) break;
            if(in[p.first][p.second]=='X') continue;
            
            fl[p.first][p.second]=true;
            
            for(int j=0;j<4;j++)
                qp.push(make_pair(p.first+mo[j],p.second+mo[(j+1)%4]));
            
        }
        while(!qp.empty())
            qp.pop();
        qp.push(make_pair(p.first,p.second));
        qp.push(make_pair(-5,-5));
        
        for(int k=0;k<h;k++)
            for(int j=0;j<w;j++)
                fl[k][j]=false;
    }
            
    printf("%d\n",ans);
    
    return 0;
}

C++: #include <iostream>
#include <queue>
using namespace std;
typedef pair<int, int> P;
const int MAX_HW = 1000;
int n, h, w, rat = 1, s[2], g[2], flag[MAX_HW][MAX_HW][2];
char town2[MAX_HW][MAX_HW];
queue <P> que;
P p;
void bfs(int sy, int sx){
	que.push(P(sy, sx));
	flag[p.first][p.second][1] = 0;
	while (que.size()){
	RE:
		p = que.front();
		que.pop();
		flag[p.first][p.second][0] = rat;
		for (int i = -1; i <= 1; i++){
			for (int j = -1; j <= 1; j++){
				if (i == 0 || j == 0){
					if (town2[p.first + i][p.second + j] != 'X'&&flag[p.first + i][p.second + j][0] != rat&&p.first + i < h&&p.first + i >= 0 && p.second + j < w&&p.second + j >= 0) {
						if (town2[p.first + i][p.second + j]-48 == rat){
							flag[p.first + i][p.second + j][1] = flag[p.first][p.second][1] + 1;
							if (rat == n) return;
							rat++;
							while (que.size()){
								que.pop();
							}
							que.push(P(p.first + i, p.second + j));
							goto RE;
						}
						flag[p.first + i][p.second + j][1] = flag[p.first][p.second][1] + 1;
						que.push(P(p.first + i, p.second + j));
					}
				}
			}
		}
	}
}
int main(){
	cin >> h >> w >> n;
	rat = 1;
	for (int i = 0; i < h; i++){
		for (int j = 0; j < w; j++){
			cin >> town2[i][j];
			if (town2[i][j] == 'S'){
				s[0] = i;
				s[1] = j;
			}
			if (town2[i][j]-48 == n){
				g[0] = i;
				g[1] = j;
			}
		}
	}
	bfs(s[0], s[1]);
	cout << flag[g[0]][g[1]][1] << endl;
	return 0;
}

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;
}