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; };
  
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]; }
  
    rep(x, H)
    {
        rep(y, W)
        {
            if (field[x][y] == 'X') { continue; }
            if (field[x][y] == 'S') { Sx = x; Sy = y; }
            //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;
}catch(std::bad_alloc){return 0;}}

C++: #include <iostream>
#include <queue>
#include <map>
#include <string>
#include <vector>
#include <string.h>

#define loop(lp) for(int lp2 = 0; lp2 < lp; lp2 ++) 
#define ascent(i,a,b) for(int i = a; i < b; i ++)

#define pb push_back

using namespace std;

int search[1010][1010];
int W, H, N;
vector<string> m;

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

int cheese = 1;
int ans = 0;

void BFS(int x, int y) {
  memset(search, 0, sizeof(search));
  search[x][y] = 1;

  queue<pair<int, pair<int, int> > > q;
  q.push(make_pair(0, make_pair(x, y)));

  while(!q.empty()) {
    pair<int, pair<int, int> > xy = q.front();
    q.pop();

    int cnt = xy.first;
    int _x = xy.second.first;
    int _y = xy.second.second;

    //   cout << " " << cnt << " " << _x << " " << _y << endl;
    ascent(i, 0, 4) {
      int xx = _x + dx[i];
      int yy = _y + dy[i];
      
      //cout << search[1][0] << endl;
      if(0 <= xx && xx < W && 0 <= yy && yy < H && search[xx][yy] == 0) {
	if(m[yy][xx] - '0' == cheese) {
	  ans += cnt+1;
	  cheese ++;
	  
	  if(cheese <= N) {
	    BFS(xx, yy);
	  }
	  else { return; }
	}
	else if(m[yy][xx] != 'X') {
	  
	  q.push(make_pair(cnt+1, make_pair(xx, yy)));
	}
      }
    }
  }
}

int main() {
  cin >> W >> H >> N;
  
  loop(H) {
    string tmp;
    cin >> tmp;
    m.pb(tmp);
  }

  int i, j;
  bool flg = false;
  for(i = 0; i < W; i ++) {
    for(j = 0; j < H; j ++) {
      if(m[j][i] == 'S') {
	//	cout << i << " " << j << endl;
	BFS(i, j);
	flg = true;
      }
    }
    if(flg) break;
  }
  //  cout << i << " " << j << endl;
  cout << ans << endl;
  return 0;
}

C++: #include<stdio.h>
#include<string.h>
#include<queue>
#include<utility>
#define MAX 0x3f3f3f3f
using namespace std;
int mat[1005][1005];
int visited[1005][1005];
int node[10][2];
int dx[4]={0,1,0,-1},dy[4]={1,0,-1,0};
int h,w,n,cur;
typedef pair<pair<int,int>,int> P;
int dfs(int no)
{
	int i,ni=node[no][0],nj=node[no][1];
	queue<P> que;
	P m;
	cur++;
	que.push(make_pair(make_pair(ni,nj),0));
	visited[ni][nj]=cur;
	int x,y;
	while(!que.empty())
	{
		
		m=que.front(),que.pop();
		for(i=0;i<4;i++)
		{
		
			x=m.first.first+dx[i];
			y=m.first.second+dy[i];
		
			if(x<0||x>=h||y<0||y>=w||visited[x][y]==cur||mat[x][y]=='X')continue;
			if(mat[x][y]-'0'==no+1)
				return m.second+1;
			que.push(make_pair(make_pair(x,y),m.second+1));
			visited[x][y]=cur;
		}
		
	}
	return -1;
}
int main()
{
	int i,j,si,sj,no=0;
	scanf("%d%d%d",&h,&w,&n);
	getchar();
	for(i=0;i<h;i++)
	{
		for(j=0;j<w;j++)
		{
			mat[i][j]=getchar();
			if(mat[i][j]=='S')
			{
				node[0][0]=i;
				node[0][1]=j;
			}
			else if(mat[i][j]>'0'&&mat[i][j]<='9')
			{
				node[mat[i][j]-'0'][0]=i;
				node[mat[i][j]-'0'][1]=j;
			}
		
		}
		getchar();
	}

	int sum=0;
	for(i=0;i<n;i++)
	{
	
		sum+=dfs(i);
	}
	printf("%d\n",sum);
	return 0;
}

C++: #include<iostream>
#include<queue>
#include<algorithm>
#include<string.h>
using namespace std;
struct nagase {
		int x;
		int y;
		int c;
		int r;
};
int kani[4]={0,1,-1,0};
int ebi[4]={1,0,0,-1};
long long map[1001][1001]={0};
int s[1001][1001];
int main(){
	queue<nagase>Q;
	nagase kotani;
	nagase yanagi;
	int h,w,n;
	cin>>h>>w>>n;
	char a;
	memset(s,0,sizeof(s));
	for(int i=0;i<h;i++){
		for(int j=0;j<w;j++){
			cin>>a;
			if(a=='S'){
				kotani.x=i;
				kotani.y=j;
				kotani.c=1;
				kotani.r=0;
				s[i][j]=1;
				Q.push(kotani);
			}
			else if(a=='X'){
				map[i][j]=-1;
			}
			else if(a=='.'){
				map[i][j]=0;
			}
			else{
				map[i][j]=(int)(a-48);
			}
		}
	}
	while(!Q.empty()){
		yanagi=Q.front();
		Q.pop();
		if(yanagi.c==map[yanagi.x][yanagi.y]){
			if(yanagi.c==n){
				cout<<yanagi.r<<endl;
				break;
			}
			while(!Q.empty()){
				Q.pop();
			}
			yanagi.c++;
			memset(s,0,sizeof(s));
			s[yanagi.x][yanagi.y]=1;
			Q.push(yanagi);
		}
		else{
			for(int i=0;i<4;i++){
				if(yanagi.x+kani[i]>=0&&yanagi.x+kani[i]<h&&yanagi.y+ebi[i]>=0&&yanagi.y+ebi[i]<w&&map[yanagi.x+kani[i]][yanagi.y+ebi[i]]!=-1&&s[yanagi.x+kani[i]][yanagi.y+ebi[i]]!=1){
					kotani=yanagi;
					kotani.x=yanagi.x+kani[i];
					kotani.y=yanagi.y+ebi[i];
					kotani.c;
					kotani.r++;
					s[yanagi.x+kani[i]][yanagi.y+ebi[i]]=1;
					Q.push(kotani);
				}
			}
		}
	}
}