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 <fstream>
#include <algorithm>
#include <vector>
#include <string>
#include <functional>
#include <array>
#include <stack>
#include <queue>
#include <chrono>
#include <numeric>

#pragma warning(disable:4996)
#define REP(i,n) for(int i = 0 ; i < n ; ++i)
typedef long long Int;

using namespace std;

struct point{
	Int j, i,step;
	point(Int i_, Int j_,Int s) :i(i_), j(j_),step(s){}
};

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

queue<point> que;
char tile[1001][1001];
int H, W;
bool ed[1001][1001];

point solve(char target)
{
	while (!que.empty()){
		point now(que.front());
		ed[now.i][now.j] = true;
		que.pop();
		REP(i, 4){
			int x = now.j + dx[i];
			int y = now.i + dy[i];

			if (x < 0 || y < 0 || x > W || y > H || ed[y][x])
				continue;

			if (tile[y][x] == target){
				return point(y, x,now.step+1);
			}

			if (tile[y][x] != 'X'){
				que.push(point(y, x, now.step + 1));
				ed[y][x] = true;
			}
		}
	}
}

int main()
{
	cin.tie(0); ios::sync_with_stdio(false);
	//fstream fs("input.txt");
	////////////ここから開始///////////
	int n(0);
	cin >> H >> W >> n;

	REP(i, 1001)REP(j, 1001){ tile[i][j] = 'X'; ed[i][j] = false; }

	REP(i, H)REP(j, W)cin >> tile[i][j];

	REP(i, H)REP(j, W){ if (tile[i][j] == 'S')que.emplace(i, j, 0); }

	for (int i = 0; i < n; ++i){
		REP(i_1, H + 1)REP(j_1, W + 1){ ed[i_1][j_1] = false; }
		point t = solve('1' + i);
		que = {};
		que.emplace(t);
	}

	cout << que.front().step << endl;

	return 0;
}

C++: #include <iostream>
#include <queue>

#define MAX_W 1000
#define MAX_H 1000
#define MAX_N 1000
#define INF -1

typedef std::pair<int, int> P;

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

int w, h, n;
int sx, sy, gx[MAX_N], gy[MAX_N];
char field[MAX_W][MAX_H];

int solve(int _sx, int _sy, int _gx, int _gy);

int main(){
    std::cin >> h >> w >> n;
    for(int i = 0; i < h; ++i){
        for(int j = 0; j < w; ++j){
            std::cin >> field[j][i];
            if(field[j][i] == 'S')
                sx = j, sy = i;
            
            else if(field[j][i] >= '0' && field[j][i] <= '9')
                gx[field[j][i] - '0'] = j, gy[field[j][i] - '0'] = i;
        }
    }
    
    int ans = 0;
    
    for(int i = 0; i < n; ++i){
        if(i == 0)
            ans += solve(sx, sy, gx[i + 1], gy[i + 1]);
        else
            ans += solve(gx[i], gy[i], gx[i + 1], gy[i + 1]);
    }
    
    std::cout << ans << std::endl;
    
    return 0;
}

int solve(int _sx, int _sy, int _gx, int _gy){
    int dis[MAX_W][MAX_H];
    std::queue<P> que;
    que.push(P(_sx, _sy));
    
    for(int i = 0; i < h; ++i){
        for(int j = 0; j < w; ++j)
            dis[j][i] = INF;
    }
    
    dis[_sx][_sy] = 0;
    
    while(que.size()){
        P p = que.front();
        que.pop();
        
        if(p.first == _gx && p.second == _gy)
            break;
        
        for(int i = 0; i < 4; ++i){
            int nx = p.first + dx[i], ny = p.second + dy[i];
            
            if(nx >= 0 && ny >= 0 && nx < w && ny < h && field[nx][ny] != 'X' && dis[nx][ny] == INF){
                que.push(P(nx, ny));
                dis[nx][ny] = dis[p.first][p.second] + 1;
            }
        }
    }
    
    return dis[_gx][_gy];
}

C++: #include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <iostream>
#include <queue>
using namespace std;
#define MAXN 1005
using namespace std;

struct node {
	int i;
	int j;
	char val;
};

int H, W, N;//H(1 <= H <= 1000)、W(1 <= W <=1000)、N(1 <= N <= 9)
char m[MAXN][MAXN];
queue<node> q;

bool flag = 0;
int t1 = 0;
char flag_m[MAXN][MAXN];
void search(int i, int j, char val)
{
	if (flag_m[i][j]<val) {
		if (m[i][j] == 'X')
		{
			return;
		}
		if (m[i][j] == '.' || m[i][j] != val)
		{
			q.push({ i, j, val });
			//flag_m[i][j] = true;
			t1++;
		}
		if (m[i][j] == val)
		{
			if (val ==(char)('0' + N))
			{
				flag = 1;
			}
			else
			{
				q.push({ i, j, val + 1 });
				//flag_m[i][j] = true;
				m[i][j] = '.';
				t1++;
			}
		}
	}
	return;
}
int main()
{
	int si, sj;
	scanf("%d %d %d", &H, &W, &N);
	for (int i = 1; i <= H; i++)
	{
		getchar();
		for (int j = 1; j <= W; j++)
		{
			scanf("%c", &(m[i][j]));
			if (m[i][j] == 'S')
			{
				si = i;
				sj = j;
			}
		}
	}

	//

	q.push({ si, sj, '1' });
	memset(flag_m, '0', sizeof(flag_m));
	int t = 1;
	int time = 0;

	while (!q.empty() && (!flag))
	{
		time++;
		t1 = 0;
		while (t-- && (!flag))
		{
			node n1 = q.front(); q.pop();
			si = n1.i; sj = n1.j;
			flag_m[si][sj] = n1.val;
			if (si > 1)
			{
				search(si - 1, sj, n1.val);
			}
			if (si < H)
			{
				search(si + 1, sj, n1.val);
			}
			if (sj > 1)
			{
				search(si, sj - 1, n1.val);
			}
			if (sj < W)
			{
				search(si, sj + 1, n1.val);
			}

		}
		t = t1;
	}
	printf("%d\n", time);
	return 1;
}

C++: #include <iostream>
#include <algorithm>
#include <queue>

using namespace std;

struct P{
  int s;
  int t;
};

struct P2{
  int s;
  int t;
  int c;
};

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

int bfs(char ch[1001][1001], P st, P go, int w, int h)
{
  bool fa[1001][1001];
  fill(&fa[0][0], &fa[1000][1000],  true);
  P2 p, q;
  queue<P2> que;
  p.s = st.s;
  p.t = st.t;
  p.c = 0;
  que.push(p);
  int c = 0;
  while(!que.empty()){
    p = que.front();
    que.pop();

    if(p.s == go.s && p.t == go.t){
      c = p.c;
      break;
    }

    for(int i = 0; i < 4; i++){
      q.s = p.s + ds[i];
      q.t = p.t + dt[i];
      if(q.s >= 0 && q.s < h && q.t >= 0 && q.t < w && fa[q.s][q.t] && ch[q.s][q.t] != 'X'){
	fa[q.s][q.t] = false;
	q.c = p.c + 1;
	que.push(q);
      }
    }
  }

  return c;
}

int main()
{
  int w, h, n, c;
  char ch[1001][1001];
  P pa[10];

  while(cin>>h>>w>>n && h && w && n){
    for(int i = 0; i < h; i++){
      for(int j = 0; j < w; j++){
	cin >> ch[i][j];
	if(ch[i][j] == 'S'){
	  pa[0].s = i;
	  pa[0].t = j;
	} else if(ch[i][j] != '.' || ch[i][j] != 'X'){
	  pa[(int)(ch[i][j]-'0')].s = i;
	  pa[(int)(ch[i][j]-'0')].t = j;
	}
      }
    }
    c = 0;

    for(int i = 0; i < n; i++){
      c += bfs(ch, pa[i], pa[i+1], w, h);
    }

    cout << c << endl;
  }

  return 0;
}