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

int H, W, N;
std::string field[1123];
int Sx, Sy, xy[11];
int 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()
{
	in >> H >> W >> N;
	rep(i, H) { in >> field[i]; }

	rep(x, H)
	{
		rep(y, W)
		{
			if (field[x][y] == 'X') { continue; }
			if (field[x][y] == 'S') { Sx = x; Sy = y; }
			else if (field[x][y] != '.') { xy[field[x][y] - '0'] = x*W + y; }
			if (x < H - 1)
			{
				if (field[x + 1][y] != 'X')
				{
					G[x*W + y].push_back({ (x + 1)*W + y,1 });
					G[(x + 1)*W + y].push_back({ x*W + y,1 });
				}
			}
			if (y < W - 1)
			{
				if (field[x][y + 1] != 'X')
				{
					G[x*W + y].push_back({ x*W + (y + 1),1 });
					G[x*W + (y + 1)].push_back({ x*W + y,1 });
				}
			}
		}
	}
	dijkstra(Sx*W + Sy);
	rep(i, N)
	{
		ans += d[xy[i + 1]];
		dijkstra(xy[i + 1]);
	}

	out << ans << std::endl;
	return 0;
}

C++: #include<iostream>
#include<queue>
#include<string>
#include <cstring>
#include<cstdio>
using namespace std;

  int used[1001][1001];
  char m[1001][1001];
  int H,W,N,sx,sy;
  
  const int dx[4]={1,0,-1,0};
  const int dy[4]={0,1,0,-1};

bool check(int x,int y){
  return x>=0&&y>=0&&x<H&&y<W&&m[x][y]!='X';
}

void debug()
{
  for(int i = 0; i < H; i++) {
    for(int j = 0; j < W; j++){
      printf("%3d", used[i][j]);
    }
    puts("");
  }
  puts("");
} 
int bfs(int p){
  memset(used, 0, sizeof used);
  queue<pair<int,int> > que;
  used[sx][sy] = 1;
  que.push(make_pair(sx,sy));
  while(!que.empty()){
    pair<int,int> pos= que.front();
    que.pop();
    for(int i=0;i<4;i++){
      int x=pos.first+dx[i];
      int y=pos.second+dy[i];
      if(check(x,y) && used[x][y] == 0){
       que.push(make_pair(x,y));
       used[x][y] = used[pos.first][pos.second] + 1;
      }
      if(m[x][y]==p+'0'){
	
       sx=x;
       sy=y;
       return used[x][y] - 1;
      }
    }
  }
}



int main()
{
  cin>>H>>W>>N;
  for(int i=0;i<H;i++){
    for(int j=0;j<W;j++){
      cin>>m[i][j];
      if(m[i][j]=='S'){
       sx=i;
       sy=j;
      }	
    }
  }
  int res=0;
  for(int i=1;i<=N;i++){
    res+=bfs(i);
  }
  cout << res << endl;
  
}

C++: #include<bits/stdc++.h>
#include<ctype.h>
#define int long long int
#define rep(a,b) for(int a=0;a<b;a++)
#define INF 1000006
using namespace std;

int tx[] = {1,0,-1,0};
int ty[] = {0,1,0,-1};
int w,h,che,sx,sy;
char bases;
int base[1003][1003],base2[1003][1003],memo[1003][1003];

int chee(int x,int y,int n){
    int ans=INF;
    if(memo[x][y]>0)return memo[x][y];
    else if(base[x][y]==n)return 0;
    else if(base[x][y]>=0){
        base[x][y]=-1;
        for(int i=0;i<4;i++){
            if(x+tx[i]>=0&&x+tx[i]<w&&y+ty[i]>=0&&y+ty[i]<h){
                ans = min(ans,chee(x+tx[i],y+ty[i],n)+1);
            }
        }base[x][y]=0;
    }return memo[x][y]=ans;
}
void sho(int b[1003][1003],int a[1003][1003]){
    rep(i,1003){
        rep(j,1003){
            b[i][j]=a[i][j];
        }
    }
}

signed main(){
    int zx[20],zy[20];
    cin >> h >> w >> che;
    rep(f,h){
        rep(s,w){
            cin >> bases;
            switch(bases){
                case 'S':sx=s;sy=f;
                case '.':base[s][f]=0;
                break;
                case 'X':base[s][f]=-1;
                break;
                default:{base[s][f]=bases - '0';
                        zx[base[s][f]]=s;
                        zy[base[s][f]]=f;
                        }

            }
        }
    }
    sho(base2,base);
    int ans=0;
    ans+=chee(sx,sy,1);
    for(int i=2;i<=che;i++){
        sho(base,base2);
        fill((int*)memo,(int*)(memo+1003),0);
        ans+=chee(zx[i-1],zy[i-1],i);
    }
    cout << ans << endl;
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 ] ;
		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 )
			{
				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 )
					{
						s.cnt++ ;
						que.push( s ) ;
					}
				}
			}
		}
		memset( came ,0 ,sizeof( came ) ) ;
		que.push( m ) ;
	}
	cout << m.cnt << endl ;
	return 0 ;
}