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<cstdio>
#include<queue>

using namespace std;
int H, W,N;
int time = 0;
int flag = 0;  //   ?志是否?束
int flagt = 0;   //   ??一个?点有几个相??点
char SearchMap[1001][1001];
int SearchFlag[1001][1001] = {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;
			}
		}
	}

	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",resultTime);

	return 1;

}

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

#define max 1005

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

int arr[max][max];
int arr_bk[max][max];
int xd[]={-1,0,1,0};
int yd[]={0,-1,0,1};
int dot,cheese,cnt;
int h,w;
int energy;

using namespace std;

void bfs(int *i,int *k)
{
    queue <node> qu;
    node tp,tp2;
    tp.x=*k;tp.y=*i;tp.c='S',tp.cnt=0;
    int n,m;
    qu.push(tp);
    for(n=0;n<h;++n)
        for(m=0;m<w;++m)
            arr_bk[n][m]=arr[n][m];
    while(!qu.empty())
    {
        tp=qu.front();
        qu.pop();
        for(n=0;n<4;n++)
        {
            tp2.x=tp.x+xd[n];
            tp2.y=tp.y+yd[n];
            tp2.c=tp.c;
            tp2.cnt=tp.cnt;
            if(tp2.x<0||tp2.x>=w||tp2.y<0||tp2.y>=h||arr_bk[tp2.y][tp2.x]=='X')
                continue;
            if(arr_bk[tp2.y][tp2.x]=='.'||arr_bk[tp2.y][tp2.x]=='S')
            {
                tp2.cnt++;
                arr_bk[tp2.y][tp2.x]='X';
                qu.push(tp2);
            }
            if(arr_bk[tp2.y][tp2.x]-48>=0&&arr_bk[tp2.y][tp2.x]-48<=9)
            {
                if(arr_bk[tp2.y][tp2.x]-48<=energy)
                {
                    energy++;
                    cheese--;
                    arr[tp2.y][tp2.x]='.';
                    tp.cnt++;
                    *k=tp2.x;*i=tp2.y;cnt+=tp.cnt;
                    return;
                }
                else
                {
                    tp2.cnt++;
                    qu.push(tp2);
                }
            }
        }
    }
}

int main()
{
    int i,k,n,x,y;
    while(scanf("%d %d %d",&h,&w,&n)==3)
    {
        cheese=0;
        for(i=0;i<h;i++)
        {
            for(k=0;k<w;k++)
            {
                scanf(" %c",&arr[i][k]);
                if(arr[i][k]=='S')
                {
                    x=k;y=i;
                }
                if(arr[i][k]>='1'&&arr[i][k]<='9')
                    cheese++;
            }
        }
        energy=1;cnt=0;
        while(cheese)
        {
            bfs(&y,&x);
        }
        printf("%d\n",cnt);
    }
    return 0;
}

C++: #include<iostream>
#include<cstdio>
#include<queue>
#define REP(i,n) for(int i=0;i<(n);i++)
#define FOR(i,a,b) for(int i=(a);i<(b);i++)

using namespace std;


struct P{
    int x;
    int y;
};

int w,h,n;
const int INF = 1e+8;
char feld[1010][1010];
int d[1010][1010];
int sx,sy,gx,gy;
int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};
int ans=0;
P che[15];


int bfs(){
    REP(i,n){
        P sp=che[i];
        sx=che[i].x;
        sy=che[i].y;
        gx=che[i+1].x;
        gy=che[i+1].y;
        queue<P> que;
        REP(y,h)REP(x,w)d[y][x]=INF;
        que.push(sp);
        d[sy][sx]=0;
        while(!que.empty()){
            P p=que.front();
            que.pop();
            int x=p.x;
            int y=p.y;
            if(x==gx&&y==gy){
                ans+=d[gy][gx];
                break;
            }
            REP(i,4){
                int nx=x+dx[i];
                int ny=y+dy[i];
                if(nx<0||ny<0&&nx>=w&&ny>=h)continue;
                if(feld[ny][nx]!='X'&&d[ny][nx]==INF){
                    P next;
                    next.x=nx;
                    next.y=ny;
                    que.push(next);
                    d[ny][nx]=d[y][x]+1;
                }
            }
        }
    }
    return 0;
}

int main(){
    cin>>h>>w>>n;
    REP(y,h){
        REP(x,w){
            scanf(" %c",&feld[y][x]);
            if(feld[y][x]=='S'){
                che[0].x=x;
                che[0].y=y;
            }else if(feld[y][x]>='1'&&feld[y][x]<='9'){
                char c=feld[y][x];
                che[c-'0'].x=x;
                che[c-'0'].y=y;
            }
        }
    }
    bfs();
    cout<<ans<<endl;
    return 0;
}