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 <bits/stdc++.h>

#define REP(i, n) for (int i = 0; i < (n); i++)
#define FOR(i, init, n) for (int i = init; i < (n); i++)
#define ALL(obj) (obj).begin(), (obj).end()
#define fi first
#define se second

using namespace std;
using ll = long long int;
using P = pair<int, int>;
using T = tuple<int, int, int>;
using edge = struct
{
    int to, cost;
};

const int MOD = 1e9 + 7;
const int iINF = 1e9;
const long long int llINF = 1e18;
const double PI = acos(-1.0);

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

char c[1010][1010];
int dist[1010][1010];
int H, W, sx, sy;

ll bfs(int num)
{
    queue<P> que;

    que.push(P{sy, sx});

    dist[sy][sx] = 0;

    while (!que.empty())
    {
        int x, y;

        tie(y, x) = que.front();
        que.pop();

        REP(i, 4)
        {
            int nx = x + dx[i], ny = y + dy[i];

            if (dist[ny][nx] != -1)
                continue;

            if (nx < 0 || ny < 0 || H <= ny || W <= nx)
                continue;

            if (c[ny][nx] == 'X')
                continue;

            if (c[ny][nx] == num + '0')
            {
                dist[ny][nx] = dist[y][x] + 1;

                sx = nx;
                sy = ny;

                return dist[ny][nx];
            }

            dist[ny][nx] = dist[y][x] + 1;

            que.push(P{ny, nx});
        }
    }
}

int main()
{
    cin.tie(0);
    ios::sync_with_stdio(false);

    int N;
    cin >> H >> W >> N;

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

            if (c[i][j] == 'S')
            {
                sx = j;
                sy = i;
            }
        }
    }

    ll ans = 0;

    REP(i, N)
    {
        memset(dist, -1, sizeof(dist));

        ans += bfs(i + 1);
    }

    cout << ans << endl;

    return 0;
}

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

#define	mp		make_pair
#define	rep(i,n)	for(int i=0;i<n;i++)

using namespace std;

typedef	pair<int,int>	pii;

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

int h,w;
char grid[1000][1000];

int shortestDistance(int x1,int y1,int x2,int y2){
	static bool visited[1000][1000];
	rep(i,h)rep(j,w)	visited[i][j]=false;
	visited[y1][x1]=true;

	queue< pair<int,pii> > qu;	qu.push(mp(0,mp(x1,y1)));
	while(1){
		pair<int,pii> a=qu.front();	qu.pop();
		int d=a.first,x=a.second.first,y=a.second.second;
		if(x==x2 && y==y2)	return d;

		rep(i,4){
			int xx=x+dx[i],yy=y+dy[i];
			if(0<=xx && xx<w && 0<=yy && yy<h && grid[yy][xx]!='X' && !visited[yy][xx]){
				visited[y][x]=true;
				qu.push(mp(d+1,mp(xx,yy)));
			}
		}
	}
}

int main(){
	int n;	scanf("%d%d%d ",&h,&w,&n);
	int cx[10],cy[10];
	rep(i,h)rep(j,w){
		scanf("%c ",grid[i]+j);
		if(grid[i][j]=='S')		cx[0]=j,cy[0]=i;
		if(isdigit(grid[i][j]))	cx[grid[i][j]-'0']=j,cy[grid[i][j]-'0']=i;
	}

	int cost=0;
	rep(i,n)	cost+=shortestDistance(cx[i],cy[i],cx[i+1],cy[i+1]);
	printf("%d\n",cost);

	return 0;
}

C++: #include<iostream>
#include<cstring>
#include<queue>
using namespace std ;
struct ST
{
	int x ;
	int y ;
	int cnt = 0 ;
} ;
bool came[ 1000 ][ 1000 ] = {{ 0 }} ;
//char map[ 1000 ][ 1000 ] ;
int main()
{
	ST m ,s ;
	queue< ST > que ;
	int n ;
	int w ,h ;
	int kyori = 0 ;
	int mx[ 4 ] = { 0 ,0 ,1 ,-1 } ;
	int my[ 4 ] = { 1 ,-1 ,0 ,0 } ;
	cin >> h >> w >> n ;
	char c = '0' ;
	char map[ h ][ w ] ;
	bool a = true ;	
	for( int i = 0 ; i < h ; i++ )
	{
		cin >> map[ i ] ;
		for( int j = 0 ; j < w ; j++ && a )
		{
			if( map[ i ][ j ] == 'S' )
			{
				m.x = j ;
				m.y = i ;
				a = false ;
			}
		}
	}
	que.push( m ) ;
	while( n )
	{
		n-- ;
		c++ ;
		while( !que.empty() )
		{
			m = que.front() ;
			que.pop() ;
			came[ m.y ][ m.x ] = 1 ;
			if( map[ m.y ][ m.x ] == c )
			{
				kyori += m.cnt ;
				while( ! que.empty() )
				{
					que.pop() ;
				}
				break ;
			}
			for( int i = 0 ; i < 4 ; i++ )
			{
				if( m.x + mx[ i ] > -1 && m.x + mx[ i ] < w && m.y +  my[ i ] > -1 && m.y + my[ i ] < h )
				{
					s = m ;
					s.x += mx[ i ] ;
					s.y += my[ i ] ;
					s.cnt++ ;
					if( map[ s.y ][ s.x ] != 'X' && came[ s.y ][ s.x ] == 0 )
					{
						que.push( s ) ;
					}
				}
			}
		}
		memset( came ,0 ,sizeof( came ) ) ;
		m.cnt = 0 ;
		que.push( m ) ;
	}
	cout << kyori << 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[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;

}