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 <queue>
#include <cctype>
#include <vector>

using namespace std;

struct Position {
    int h, w, time, strength;
    Position (int h, int w, int t, int s): h(h), w(w), time(t), strength(s) {}
};

const int max_h = 1005;
const int max_w = 1005;
int g_h, g_w, g_strength, g_max_strength, si, sj;
char mat[max_h][max_w];
pair<int, int> factories[20];
int dh[] = {0, 1, 0, -1};
int dw[] = {1, 0, -1, 0};

int main() {
    scanf("%d%d%d", &g_h, &g_w, &g_max_strength);
    for (int i = 0; i < g_h; i++) {
        getchar();
        for (int j = 0; j < g_w; j++) {
            mat[i][j] = getchar();
            if (mat[i][j] == 'S') {
                si = i;
                sj = j;
                mat[i][j] = '.';
            } else if (isdigit(mat[i][j])) {
                factories[mat[i][j]-'0'].first = i;
                factories[mat[i][j]-'0'].second = j;
                mat[i][j] = '.';
            }
        }
    }
    queue<Position> q;
    g_strength = 1;
    q.push(Position(si, sj, 0, 1));
    int result = -1;
    while (!q.empty()) {
        Position p = q.front();
        q.pop();
        if (p.strength < g_strength) continue;
        pair<int, int> f = factories[p.strength];
        if (p.h == f.first && p.w == f.second) {
            if (p.strength == g_max_strength) {
                result = p.time;
                break;
            }
            p.strength++;
            g_strength++;
        }
        for (int i = 0; i < 4; i++) {
            int w = p.w + dw[i];
            int h = p.h + dh[i];
            if (w >= 0 && w < g_w && h >= 0 && h < g_h &&
                    (mat[h][w] == '.' || (isdigit(mat[h][w]) && p.strength+'0' > mat[h][w]))) {
                mat[h][w] = p.strength+'0';
                q.push(Position(h, w, p.time+1, p.strength));
            }
        }
    }
    printf("%d\n", result);
    return 0;
}

C++: #include <iostream>
#include <queue>
using namespace std;

typedef pair<int, int> P;

const int MAX_H = 1000, MAX_W = 1000;
const int INF = 1000000000;
int H, W, N;
char field[MAX_H][MAX_W];
int d[MAX_H][MAX_W];
int dx[4] = {1,0,-1,0}, dy[4] = {0,1,0,-1};
int result = 0;
P start, goal;

int bfs(P start, P goal);

int main(){
	cin >> H;
	cin >> W;
	cin >> N;
	for(int i=0; i<H; i++){
		cin >> field[i];
	}

	for(int i=0; i<H; i++){
		for(int j=0; j<W; j++){
			if(field[i][j] == 'S'){
				goal.first = i;
				goal.second = j;
			}
		}
	}

	for(int n=1; n<=N; n++){
		start.first = goal.first;
		start.second = goal.second;

		for(int i=0; i<H; i++){
			for(int j=0; j<W; j++){
				if(field[i][j] == n+'0'){
					goal.first = i;
					goal.second = j;
				}
			}
		}
		result += bfs(start, goal);
	}

	cout << result << endl;

	return 0;
}

int bfs(P start, P goal){
	for(int i=0; i<MAX_H; i++)
		for(int j=0; j<MAX_W; j++) d[i][j] = INF;

	queue<P> que;
	que.push(start);
	d[start.first][start.second] = 0;

	while(que.size()){
		P p = que.front();
		que.pop();

		if(p.first==goal.first && p.second==goal.second) break;

		for(int i=0; i<4; i++){
			int xnew = p.first + dx[i];
			int ynew = p.second + dy[i];

			if(0<=xnew && xnew<H && 0<=ynew && ynew<W && field[xnew][ynew]!='X' && d[xnew][ynew]==INF){
				que.push(P(xnew, ynew));
				d[xnew][ynew] = d[p.first][p.second] + 1;
			}
		}
	}

	return d[goal.first][goal.second];
}

C++: #include<iostream>
#include<cstdio>
#include<string>
#include<map>
#include<algorithm>
using namespace std;
typedef pair<int,int> P;

int bfs();
int INF=1000000000;
int h,w,n;
int dx[4] = {1,0,-1,0};
int dy[4] = {0,1,0,-1};
int sx,sy;
int good[1111][1111];
int ans=0;
char life="0";
char map[1111][1111];

int main(){
  cin >> h >> w >> n;
  for(int i=0;i<h;i++){
    for(int j=0;j<w;j++){
      cin >> map[i][j];
      if(map[i][j] == 'S'){
	sy = i;
	sx = j;
      }
    }
  }
  for(int i=1;i<n+1;i++){
    life++;
    ans += bfs();
    cout << ans << endl;
  }
}


int bfs(){
  pueue<P> pue;
  for(int i=0;i<h;i++){
    for(int j=0;j<w;j++){
      good[i][j] = INF;
    }
  }
  pue.push(P(sy,sx));
  d[sy][sx] = 0;
 
  while(que.size()){
    P p=pue.front(); que.pop();
    if(map[p.first][p.second] < life){
      sy = p.first;
      sx = p.second;
      break;
    }
    for(int i=0;i<4;i++){
      int nx = p.first + dy[i];
      int ny = p.second + dx[i];
      if(0 <= nx && nx < N && 0 <= ny && ny < M && map[ny][nx] != 'X' && good[ny][nx] == INF){
	good[ny][nx] = good[p.first][p.second] + 1;
      }
    }
  }
  return good[sy][sx];
}

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

using namespace std;

int h, w;
char n;
char N[1002][1002];
bool p_flag[1002][1002] = { 0 };
int depth[1002][1002] = { 0 };

int main(){
	char next;
	int x, y, time = 0;
	int sx, sy;
	const int dx[4] = { 1, 0, -1, 0 };
	const int dy[4] = { 0, 1, 0, -1 };

	cin >> h >> w >> n;

	for (int i = 0; i < 1002; i++){
		for (int j = 0; j < 1002; j++){
			N[j][i] = 'X';
		}
	}
	for (int i = 1; i <= h; i++){
		for (int j = 1; j <= w; j++){
			cin >> N[j][i];
			if (N[j][i] == 'S'){
				sx = j;
				sy = i;
			}
		}
	}

	queue <pair<int, int>> q;
	q.push(pair<int, int>(sx, sy));
	next = '1';
	bool b_flag = 0;
	p_flag[sx][sy] = 1;
	while (true){
		if (b_flag) break;
		x = q.front().first;
		y = q.front().second;
		q.pop();
		cout << x << " " << y << endl;
		for (int d = 0; d < 4; d++){
			if (N[x + dx[d]][y + dy[d]] != 'X'){
				if (depth[x + dx[d]][y + dy[d]] == 0) depth[x + dx[d]][y + dy[d]] = depth[x][y] + 1;
				if (p_flag[x + dx[d]][y + dy[d]] == 0){
					if (N[x + dx[d]][y + dy[d]] == next){
						if (next == n){
							cout << depth[x + dx[d]][y + dy[d]] << endl;
							b_flag = 1;
							break;
						}
						else{
							next = next + 1;
							while (!q.empty()) q.pop();
							for (int i = 0; i < 1002; i++){
								for (int j = 0; j < 1002; j++){
									p_flag[j][i] = false;
								}
							}
							q.push(pair<int, int>(x + dx[d], y + dy[d]));
							p_flag[x + dx[d]][y + dy[d]] = 1;
							int dep = depth[x + dx[d]][y + dy[d]];
							for (int i = 0; i < 1002; i++){
								for (int j = 0; j < 1002; j++){
									depth[j][i] = 0;
								}
							}
							depth[x + dx[d]][y + dy[d]] = dep;
							break;
						}
					}
					else {
						q.push(pair<int, int>(x + dx[d], y + dy[d]));
						p_flag[x + dx[d]][y + dy[d]] = 1;
					}
				}
			}
		}
	}
}