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 <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <ctime>

using namespace std;

inline int toInt(string s) {int v; istringstream sin(s);sin>>v;return v;}
template<class T> inline string toString(T x) {ostringstream sout;sout<<x;return sout.str();}
template<class T> inline T sqr(T x) {return x*x;}

typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<string> vs;
typedef pair<int, int> pii;
typedef long long ll;

#define all(a)  (a).begin(),(a).end()
#define rall(a) (a).rbegin(), (a).rend()
#define pb push_back
#define mp make_pair
#define each(i,c) for(typeof((c).begin()) i=(c).begin(); i!=(c).end(); ++i)
#define exist(s,e) ((s).find(e)!=(s).end())
#define range(i,a,b) for(int i=(a);i<(b);++i)
#define rep(i,n)  range(i,0,n)
#define clr(a,b) memset((a), (b) ,sizeof(a))
#define dump(x)  cerr << #x << " = " << (x) << endl;
#define debug(x) cerr << #x << " = " << (x) << " (L" << __LINE__ << ")" << " " << __FILE__ << endl;

const double eps = 1e-10;
const double pi  = acos(-1.0);
const ll inf =1LL << 62;

struct node {
	int x;
	int y;
	int c;
};

bool check[1010][1010];
string maze[1010];
int hmax=1;

int main(void){
	int H,W,n;
	cin >> H >> W >> n;
	rep(i,H) cin >> maze[i];
	node init;
	rep(i,H) rep(j,W){
		check[i][j]=false;
		if(maze[i][j]=='S'){
			init.x=j;
			init.y=i;
			init.c=0;
		}
	}
	int ans=0;
	rep(j,n){
	//	cout << j << endl;
		queue <node> q;
		q.push(init);
		int dx[4]={1,0,-1,0};
		int dy[4]={0,1,0,-1};
		while(!q.empty()){
			node cur;
			cur=q.front();q.pop();
			// テァツ渉セテ・ツ慊ィテ、ツスツ催ァツスツョテ」ツ?ョテ・ツ按、テ・ツョツ堙・ツ?ヲテァツ青?
			if(check[cur.y][cur.x])
				continue;
			if(hmax==(maze[cur.y][cur.x]-'0')){
				ans+=cur.c;
				hmax++;
				break;
			}
			//テ」ツ??ヲツャツ。テ」ツ?ョテァツ環カテヲツ?凝」ツ?クテ」ツ?ョテゥツ?キテァツァツサ
			rep(i,4){
				node next;
				next.x=cur.x+dx[i];
				next.y=cur.y+dy[i];
				next.c=cur.c+1;
				if(0<=next.x&&next.x<W&&0<=next.y&&next.y<H&&maze[next.y][next.x]!='X')
					q.push(next);
			}	
		}
		rep(k,H) rep(l,W){
			check[k][l]=false;
			if(maze[k][l]==('0'+(hmax-1)) ){
				init.x=l;
				init.y=k;
				init.c=0;
			}
		}
	}
	cout << ans << endl;
	return 0;
}

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

using namespace std;
int H, W,N;
int flag = 0;  //   ?志是否?束
int flagt = 0;   //   ??一个?点有几个相??点
char SearchMap[1005][1005];
int SearchFlag[1005][1005] = {0};
struct node
{
	int IndexX;
	int IndexY;
	int value;
};

queue<node> q;                                                            

void FoundTheNext(int x,int y,int val)
{                                     
	if (SearchFlag[x][y] < val)
	{
		if (SearchMap[x][y] == 'X')
			return;
		if (SearchMap[x][y] - '0' == val)
		{
			if (val == N)
				flag = 1;
			else
			{
				q.push({ x,y,val + 1 });
				SearchMap[x][y] = '.';
				flagt++;
			}
			
		}
		if (SearchMap[x][y] == '.'|| SearchMap[x][y]-'0'!=val)
		{
			q.push({ x,y,val});
			flagt++;
		}
		return;
	}
	
}

int main()
{
	scanf("%d %d %d",&H,&W,&N);
	int starti = 0, startj = 0;  //  ???始的位置

	for (int i = 1; i <= H; i++)
	{
		getchar();
		for (int j = 1; j <= W; j++)
		{
			scanf("%c", &(SearchMap[i][j]));
			if (SearchMap[i][j] == 'S')
			{
				starti = i;
				startj = j;
			}
		}
	}
	if (H == 1 && W == 1)
		printf("%d\n",0);
	else
	{
		q.push({ starti,startj,1 });  //  ?始体力?1
		int resultTime = 0;   //  ??走的?数、??

		int t1 = 1;

		while (!q.empty() && flag == 0)
		{

			resultTime++;
			flagt = 0;

			while (t1--&&flag == 0)
			{
				node nodeflag = q.front();

				int x = nodeflag.IndexX, y = nodeflag.IndexY, value = nodeflag.value;

				q.pop();

				SearchFlag[x][y] = value;   //   ?置??数据的?

				if (x > 1)
					FoundTheNext(x - 1, y, value);
				if (x < H)
					FoundTheNext(x + 1, y, value);
				if (y > 1)
					FoundTheNext(x, y - 1, value);
				if (y < W)
					FoundTheNext(x, y + 1, value);
			}
			t1 = flagt;
		}


		if (flag == 1)
			printf("%d\n", resultTime);
	}
	
	return 1;

}

C++: #include <cstdio>
#include <cstdlib>
#include <queue>

char map[1000][1000];
int check[1000][1000];
int cx[10];
int cy[10];

int main(){
	int i,j,k,l,h,w,ch,pd;
	int tex,tey,ted;
	std::queue<int> qx;
	std::queue<int> qy;
	std::queue<int> qd;

	scanf("%d %d %d",&h,&w,&ch);
	scanf("%c",&map[0][0]);
	for(i=0;i<h;i++){
		for(j=0;j<=w;j++){
			scanf("%c",&map[i][j]);
			if(map[i][j]=='S'){cy[0]=i; cx[0]=j;}
			if(map[i][j]=='1'){cy[1]=i; cx[1]=j;}
			if(map[i][j]=='2'){cy[2]=i; cx[2]=j;}
			if(map[i][j]=='3'){cy[3]=i; cx[3]=j;}
			if(map[i][j]=='4'){cy[4]=i; cx[4]=j;}
			if(map[i][j]=='5'){cy[5]=i; cx[5]=j;}
			if(map[i][j]=='6'){cy[6]=i; cx[6]=j;}
			if(map[i][j]=='7'){cy[7]=i; cx[7]=j;}
			if(map[i][j]=='8'){cy[8]=i; cx[8]=j;}
			if(map[i][j]=='9'){cy[9]=i; cx[9]=j;}
		}
	}
	for(i=0;i<h;i++){
		for(j=0;j<=w;j++)check[i][j]=0;
	}

	i=0;
	while(i<ch){
		qx.push(cx[i]); qy.push(cy[i]); qd.push(0);
		++i;
		while(!qx.empty()){
			tex=qx.front(); tey=qy.front(); ted=qd.front();
			qx.pop(); qy.pop(); qd.pop();
			check[tey][tex]=1;
			if(tey==cy[i] && tex==cx[i]){
				pd+=ted;
				while(!qx.empty())qx.pop();
				while(!qy.empty())qy.pop();
				while(!qd.empty())qd.pop();
				for(k=0;k<h;k++){
					for(l=0;l<=w;l++)check[k][l]=0;
				}
				break;
			}
			++ted;
			if(tex+1<w && map[tey][tex+1]!='X' && check[tey][tex+1]==0){
				qx.push(tex+1); qy.push(tey); qd.push(ted);
			}
			if(tex-1>=0 && map[tey][tex-1]!='X' && check[tey][tex-1]==0){
				qx.push(tex-1); qy.push(tey); qd.push(ted);
			}
			if(tey+1<h && map[tey+1][tex]!='X' && check[tey+1][tex]==0){
				qx.push(tex); qy.push(tey+1); qd.push(ted);
			}
			if(tey-1>=0 && map[tey-1][tex]!='X' && check[tey-1][tex]==0){
				qx.push(tex); qy.push(tey-1); qd.push(ted);
			}
		}
	}

	printf("%d\n",pd);
	return 0;
}