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<cmath>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
#include<stack>
#include<set>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int MAX_N=100000;
const int INF = 0x3f3f3f3f;
int n,m,k;
char map[1010][1010];
bool vis[1010][1010];

struct p{
	int x;
	int y;
	int step;
};
int ans=0;

bool yesorno(p x){
	if(x.x<1||x.x>m||x.y<1||x.y>n||map[x.y][x.x]=='X'||vis[x.y][x.x]==1)
		return 0;
	return 1;
}

int sx[4]={0,0,1,-1};
int sy[4]={1,-1,0,0};
void bfs(p st,int ww){
	memset(vis,0,sizeof(vis));
	if(ww==k)
		return;
	int temp=0;
	queue<p> q;
	q.push(st);
//	cout<<st.step<<" "<<ww<<" "<<k<<endl;
	while(!q.empty()){
		
		p ne=q.front();
		q.pop();
		if(map[ne.y][ne.x]==(char)'0'+ww+1){
			ans=ne.step;
			bfs(ne,ww+1);
			return;
		}
		for(int i=0;i<4;i++){
			p tem=ne;
			tem.x=tem.x+sx[i];
			tem.y=tem.y+sy[i];
			tem.step++;
			if(yesorno(tem)){
				q.push(tem);
				vis[tem.y][tem.x]=1;
			}
				
		}
	}
}
int main(){
	ios::sync_with_stdio(false);
	while(cin>>n>>m>>k){
		memset(vis,0,sizeof(vis));
		p st;
		for(int i=1;i<=n;i++){
			for(int j=1;j<=m;j++){
				cin>>map[i][j];
				if(map[i][j]=='S'){
					st.x=j;
					st.y=i;
					st.step=0;
				}
			}
		}
		bfs(st,0);
		cout<<ans<<endl;
	}


	return 0;
}

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

C++: #include<bits/stdc++.h>
using namespace std;
#define REP(i,n) for(int i=0;i<n;++i)
string s[1010];
int chy[10], chx[10]; //cheese
int d[1010][1010]; //min time
int dx[] = {1, 0, -1, 0};
int dy[] = {0, 1, 0, -1};
int h, w, n, ans;

void bfs(){
  REP(i,n){
    int sy = chy[i], sx = chx[i];
    int gy = chy[i+1], gx = chx[i+1];
    queue<int> qy, qx;
    
    qy.push(sy); qx.push(sx);
    REP(j,h) REP(k,w) d[j][k] = 1e9; //new check
    d[sy][sx] = 0; //first time

    while(!qy.empty()){
      int posy = qy.front(); qy.pop();
      int posx = qx.front(); qx.pop();
      if(posy == gy && posx == gx){
        ans += d[gy][gx];
        break;
      }
      REP(j,4){
        int y = posy + dy[j], x = posx + dx[j];
        if(y < 0 || h <= y || x < 0 || w <= x){ //not allowed range
          continue;
        }
        if(d[y][x] == 1e9 && s[y][x] != 'X'){
          d[y][x] = d[posy][posx] + 1; //previous time + 1
          qy.push(y); qx.push(x);
        }
      }
    }
  }
}
int main(){
  cin>>h>>w>>n;
  REP(i, h){
    cin>>s[i];
    
    REP(j, w){
      if(s[i][j] == 'S'){
        chy[0] = i;
        chx[0] = j;
      }else if('1' <= s[i][j] && s[i][j] <= '9'){
        chy[s[i][j] - '0'] = i;
        chx[s[i][j] - '0'] = j;
      }
    }
  }    
  bfs();
  cout<<ans<<endl;
  return 0;
}

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

	for (int i = 1; i <= h; i++){
	for (int j = 1; j <= w; j++){
			cout << depth[j][i] << " ";
		}
		cout << endl;
	};
}