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 <sstream>
#include <cstdlib>
#include <queue>

using namespace std;

const int INF = 100000000;
const int MAX_W = 100;
const int MAX_H = 100;
int H, W, N;
char field[MAX_H][MAX_W] = {'#'};
int d[MAX_H][MAX_W] = {INF};
typedef pair<int, int> P;
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0, -1};

int main() {
    queue<P> que;
    P start;
    int pow = 1;
    while (std::cin >> H >> W >> N, H) {
        for (int i = 0; i < H; i++) {
            std::cin >> field[i];
        }
        for (int i = 0; i < H; i++) {
            for (int j = 0; j < W; j++) {
                d[i][j] = INF;
                if (field[i][j] == 'S') {
                    start = P(i, j);
                }
            }
        }
        que.push(start);
        d[start.first][start.second] = 0;
        int count = 0;
        while (que.size()) {
            P p = que.front();
            que.pop();
            if (field[p.first][p.second] == '0' + N and N <= pow) {
                count = d[p.first][p.second];
                break;
            }

            for (int i = 0; i < 4; i++) {
                int nx = p.second + dx[i];
                int ny = p.first + dy[i];
                if (nx >= 0 and ny >= 0 and nx < W and ny < H and field[ny][nx] != 'X' and d[ny][nx] == INF) {
                    if (field[ny][nx] == '.') {
                        que.push(P(ny, nx));
                        d[ny][nx] = d[p.first][p.second] + 1;
                    } else {
                        if (field[ny][nx] <= '0' + pow) {
                            //cout << "pow:" << pow << ", cheese:" << field[ny][nx] << endl;
                            int s = d[p.first][p.second];
                            field[ny][nx] = '.';
                            for (int i = 0; i < H; i++) {
                                for (int j = 0; j < W; j++) {
                                    d[i][j] = INF;
                                }
                            }


                            while (que.size()) {
                                que.pop();
                            }
                            que.push(P(ny, nx));
                            d[ny][nx] = s + 1;
                            if(pow == N) {
                                field[ny][nx] = '0' + N;
                            }
                            pow++;
                            break;
                        } else {
                            que.push(P(ny, nx));
                            d[ny][nx] = d[p.first][p.second] + 1;
                        }
                    }
                }
            }
        }

        std::cout << count << std::endl;
        break;
    }

    return 0;
}

C++: #include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int h,w,n;
char table[1001][1001];
bool visited[1001][1001];
int dx[]={0,0,1,-1};
int dy[]={1,-1,0,0};
int depth;
void dfs(int sx,int sy,char next,int now){
  if(now >= depth) return;
  if(table[sy][sx]==next) depth = now;
  visited[sy][sx]=1;
  for(int i=0;i<4;++i){
    int mx=sx+dx[i],my=sy+dy[i];
    if(mx<0||my<0) continue;
    if(mx>=w||my>=h) continue;
    if(visited[my][mx]) continue;
    if(table[my][mx]=='X') continue;
    dfs(mx,my,next,now+1);
  }
  visited[sy][sx]=0;
}
int main(){
  scanf("%d%d%d",&h,&w,&n);
  for(int i=0;i<h;++i) scanf("%s",table[i]);
  for(int i=0;i<h;++i){
    for(int j=0;j<w;++j) if(table[i][j]=='S') table[i][j]='0';
  }
  int ans = 0;
  for(int hp=0;hp<n;++hp){
    depth = h*w+1;
    memset(visited,0,sizeof(visited));
    for(int i=0;i<h;++i){
      for(int j=0;j<w;++j){
	if(table[i][j]==hp+'0'){
	  dfs(j,i,'0'+hp+1,0);
	  ans+=depth;
	}
      }
    }
  }
  printf("%d\n",ans);
  return 0;
}

C++: //Bokann ga bokka--nn!!
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <string>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <functional>
#include <iostream>
#include <map>
#include <set>
using namespace std;
typedef pair<int,int> P;
typedef pair<P,int> P1;
typedef pair<P,P> P2;
#define pu push
#define pb push_back
#define mp make_pair
#define eps 1e-7
#define INF 2000000000
char f[1005][1005];
int vis[1005][1005]={};

int main(){
	int h,w,n;
	cin >> h >> w >> n;
	for(int i=0;i<h;i++)
	{
		scanf("%s",f[i]);
	}
	P za[10];
	for(int i=0;i<h;i++)
	{
		for(int j=0;j<w;j++)
		{
			if(f[i][j]=='S')
			{
				za[0]=mp(i,j);
			}
			if(f[i][j]-'0'>=1 && f[i][j]-'0'<=9)
			{
				za[f[i][j]-'0']=mp(i,j);
			}
		}
	}
	int ret=0;
	for(int i=0;i<n;i++)
	{
		queue<P1>que;
		que.push(mp(za[i],0));
		memset(vis,0,sizeof(vis));
		while(1)
		{
			P1 p=que.front(); que.pop();
			int x=p.first.first;
			int y=p.first.second;
			int z=p.second;
			if(p.first==za[i+1]) { ret+=z; break;}
			if(vis[x][y]) continue;
			vis[x][y]=true;
			int dx[4]={1,0,-1,0};
			int dy[4]={0,1,0,-1};
			for(int j=0;j<4;j++)
			{
				if(0<=x+dx[j] && x+dx[j]<h && 0<=y+dy[j] && y+dy[j]<w && f[x+dx[j]][y+dy[j]]!='X')
				{
					que.push(mp(mp(x+dx[j],y+dy[j]),z+1));
				}
			}
			
		}
	}
	cout << ret << endl;
}

C++: #include<bits/stdc++.h>
using namespace std;
using Int = long long;

template<typename T>
vector<T> make_v(size_t a){return vector<T>(a);}
template<typename T>
vector<vector<T> > make_v(size_t a,size_t b){
  return vector<vector<T> >(a,make_v<T>(b));
}
template<typename T>
vector<vector<vector<T> > > make_v(size_t a,size_t b,size_t c){
  return vector<vector<vector<T> > > (a,make_v<T>(b,c));
}

template<typename T,typename V>
typename enable_if<is_class<T>::value==0>::type
fill_v(T &t,const V &v){t=v;}

template<typename T,typename V>
typename enable_if<is_class<T>::value!=0>::type
fill_v(T &t,const V &v){
  for(auto &e:t) fill_v(e,v);
}

//INSERT ABOVE HERE
signed main(){
  Int h,w,n;
  cin>>h>>w>>n;
  vector<string> s(h);
  for(Int i=0;i<h;i++) cin>>s[i];

  auto dp=make_v<Int>(n+1,h,w);
  fill_v(dp,-1);
  
  Int y,x,d=0;
  for(Int i=0;i<h;i++)
    for(Int j=0;j<w;j++)
      if(s[i][j]=='S')
	y=i,x=j;

  using T = tuple<Int, Int, Int>;
  queue<T> q;
  dp[d][y][x]=0;
  q.emplace(d,y,x);

  auto in=[&](Int y,Int x){return 0<=y&&y<h&&0<=x&&x<w;};
  Int dy[]={0,0,1,-1};
  Int dx[]={1,-1,0,0};
  while(!q.empty()){
    tie(d,y,x)=q.front();q.pop();
    for(Int k=0;k<4;k++){
      Int ny=y+dy[k],nx=x+dx[k],nd=d;
      if(!in(ny,nx)||s[ny][nx]=='X') continue;
      if(s[ny][nx]=='0'+(d+1)) nd++;
      if(~dp[nd][ny][nx]) continue;
      dp[nd][ny][nx]=dp[d][y][x]+1;
      q.emplace(nd,ny,nx);
    }
  }
  
  for(Int i=0;i<h;i++)
    for(Int j=0;j<w;j++)
      if(s[i][j]=='0'+n)
	cout<<dp[n][i][j]<<endl;
  
  return 0;
}