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

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

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

using namespace std;
int H, W, N;
char map[1003][1003];
int dist[1003][1003];

int bfs(char s, char t) {
    queue<int> que_x, que_y;
    rep(y, 1003) rep(x, 1003) dist[y][x] = -1;
    rep(y, H) rep(x, W) {
        if (s == map[y][x]) {
            dist[y][x] = 0;
            que_y.push(y);
            que_x.push(x);
        }
    }

    int ret = 0;
    while (que_x.size()) {
        int x = que_x.front();
        int y = que_y.front();
        que_x.pop();
        que_y.pop();
        if (map[y][x] == t) {
            ret = dist[y][x];
            break;
        }
        rep(k, 4) {
            int ny = y + dy[k];
            int nx = x + dx[k];
            if (ny < 0 || H <= ny) continue;
            if (nx < 0 || W <= nx) continue;
            if (map[ny][nx] == 'X') continue;
            if (dist[ny][nx] != -1) continue;
            dist[ny][nx] = dist[y][x] + 1;
            que_x.push(nx);
            que_y.push(ny);
        }
    }
    return ret;
}

void solve() {
    int ans = 0;

    ans += bfs('S', '1');
    rep(i, N - 1) ans += bfs(i + '1', i + '2');
    cout << ans << endl;
}

int main() {
    cin >> H >> W >> N;
    rep(y, H) cin >> map[y];
    solve();
}

C++: #include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#include <stack>
#include <array>
#include <deque>
#include <algorithm>
#include <utility>
#include <cstdint>
#include <functional>
#include <iomanip>
#include <numeric>
#include <assert.h>
#include <bitset>
 
#define MOD 1000000007
#define INF 11234567890
#define in std::cin
#define out std::cout
#define rep(i,N) for(LL i=0;i<N;++i)
typedef long long int LL;
typedef std::pair<LL, LL> P;
struct edge { LL to, cost; };
 
LL H, W, N;
std::string field[1123];
LL Sx, Sy, xy[11];
LL ans;
 
LL d[1123456];
std::vector<edge>G[1123456];
void dijkstra(LL s)
{
    std::priority_queue<P, std::vector<P>, std::greater<P>>que;
    std::fill(d, d + H * W + 1, INF);
    d[s] = 0;
    que.push(P(0, s));
    while (!que.empty())
    {
        P p = que.top(); que.pop();
        LL v = p.second;
        if (d[v] < p.first) { continue; }
        rep(i, G[v].size())
        {
            edge e = G[v][i];
            if (d[e.to] > d[v] + e.cost)
            {
                d[e.to] = d[v] + e.cost;
                que.push(P(d[e.to], e.to));
            }
        }
    }
}
 
int main()
{
    try {
        in >> H >> W >> N;
        rep(i, H) { in >> field[i]; }
 return 0;
        rep(h, H)
        {
            rep(w, W)
            {
                if (field[h][w] == 'X') { continue; }
                if (field[h][w] == 'S') { Sx = h; Sy = w; }
                if (field[h][w] != '.') { xy[field[h][w] - '0'] = h*W + w; }
                if (h < H - 1)
                {
                    if (field[h + 1][w] != 'X')
                    {
                        G[h*W + w].push_back({ (h + 1)*W + w,1 });
                        G[(h + 1)*W + w].push_back({ h*W + w,1 });
                    }
                }
                if (w < W - 1)
                {
                    if (field[h][w + 1] != 'X')
                    {
                        G[h*W + w].push_back({ h*W + (w + 1),1 });
                        G[h*W + (w + 1)].push_back({ h*W + w,1 });
                    }
                }
            }
        }
        //dijkstra(Sx*W + Sy);
        //rep(i, N)
        //{
        //  ans += d[xy[i + 1]];
        //  dijkstra(xy[i + 1]);
        //}
 
        out << ans << std::endl;
        return 0;
    }
    catch (std::bad_alloc) { return 0; }
    catch (...) { 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 mx[ 4 ] = { 0 ,0 ,1 ,-1 } ;
	int my[ 4 ] = { 1 ,-1 ,0 ,0 } ;
	cin >> h >> w >> n ;
	char c = '0' ;
	bool a = true ;	
	for( int i = 0 ; i < h ; i++ )
	{
		cin >> map[ i ] ;
		if( a )
		{
			for( int j = 0 ; j < w ; j++ && a )
			{
				if( map[ i ][ j ] == 'S' )
				{
					m.x = j ;
					m.y = i ;
					a = false ;
				}
			}
		}
	}
	que.push( m ) ;
	int cnt = 0 ;
	while( n )
	{
		n-- ;
		c++ ;
		while( !que.empty() )
		{
			m = que.front() ;
			que.pop() ;
			if( came[ m.y ][ m.x ] == 1 )continue ;
			came[ m.y ][ m.x ] = 1 ;
			if( map[ m.y ][ m.x ] == c )
			{
				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 ) ) ;
		que.push( m ) ;
	}
	cout << m.cnt << endl ;
	return 0 ;
}