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++: /*
AOJ 0558 Cheese

?¢???????H * W?????°?????????N????\¶?????\?????????????????§??¬??????1-N????\¶????????????????????????????´????????????????????????\???????\¶??????
???????????????????????????????§???¶???1?????????????????\???????\¶?????????????¢????1???????????\????????????????¬???????
????????????????????¬????????§??????????????????????\¶??????
????????????????????°??°????????????????¢????????????????????\???????????????¶??´1????????????????¢??????????????????°???
??°??°??\????????¶???????????°??\??\???????\¶??????????\¶?????¶??´?????????????????????????\¶???????°???¨??¶???

?????\????¬¬??????????????´??°H(1 <= H <= 1000)???W(1 <= W <=1000)???N(1 <= N <= 9)???
??????H???W????????°?????? ???.???????????°??? ???X??????????¢??????????S?????????????´???? 1-N??£??¨??¬??????1-N????\¶????????\??????
 */
#include <assert.h>
#include <ctype.h>
#include <float.h>
#include <limits.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>

#include <algorithm>
#include <complex>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <vector>
using namespace std;

#define SZ(a) (int)(a).size()
#define FOR(i,a,b) for (int i=(a); i<=(b); ++i)
#define REP(i,n) for (int i=0; i<(n); ++i)
#define ALL(c) c.begin(), c.end()
#define CLR(c,n) memset(c, n, sizeof(c))
#define TR(it, c) for(typeof(c.begin()) it = c.begin();it != c.end(); ++it)
#define CONTAIN(it, c) (c.find(it) != c.end())
typedef vector<int> VI;
typedef pair<int, int> PII;
template <class T> void checkmin(T &a, T b) { if (b<a) a=b; }
template <class T> void checkmax(T &a, T b) { if (b>a) a=b; }

const int N=1024;
int h, w, n;
char b[N][N];
int dist[N][N];
int tx[10], ty[10];
int dx[4] = { -1, 0, 1, 0 };
int go(int x1, int y1, int x2, int y2) {
  CLR(dist, -1);
  dist[x1][y1] = 0;
  queue<PII> q;
  q.push(PII(x1, y1));
  while (!q.empty() && dist[x2][y2] == -1) {
    x1 = q.front().first, y1 = q.front().second;
    q.pop();
    REP(dir, 4) {
      int x = x1 + dx[dir], y = y1 + dx[dir^1];
      if (x < 0 || x >= h || y < 0 || y >= w) continue;
      if (dist[x][y] != -1 || b[x][y] == 'X') continue;
      dist[x][y] = dist[x1][y1] + 1;
      q.push(PII(x, y));
    }
  }
  return dist[x2][y2];
}

int main(int argc, char *argv[]) {
  while (scanf("%d%d%d", &h, &w, &n) == 3) {
    REP(i, h) scanf("%s", b[i]);
    REP(i, h) REP(j, w) {
      if (b[i][j] == 'S') tx[0] = i, ty[0] = j;
      else if (b[i][j] >= '1' && b[i][j] <= '9') {
        tx[b[i][j]-'0'] = i;
        ty[b[i][j]-'0'] = j;
      }
    }
    int ans = 0;
    REP(i, n) ans += go(tx[i], ty[i], tx[i+1], ty[i+1]);
    printf("%d\n", ans);
  }
}

C++: #include <bits/stdc++.h>
#define PB push_back
#define MP make_pair
#define REP(i,n) for (int i=0;i<(n);i++)
#define ALL(a) (a).begin(),(a).end()
#define INF 1000000001
#define MOD 100000
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> P;
const ull B=100000007;
int dx[4]={-1,0,1,0};
int dy[4]={0,-1,0,1};
struct A{int x,y,cost;};
int main(){
      int h,w,n,fin=-1;
      int x[11],y[11];
      memset(x,-1,sizeof(x));
      memset(y,-1,sizeof(y));
      cin>>h>>w>>n;
      char c;
      bool fld[1000][1000];
      REP(i,h)REP(j,w){
            cin>>c;
            if(c=='.')fld[j][i]=true;
            else if(c=='X')fld[j][i]=false;
            else if(c=='S'){
                  fld[j][i]=true;
                  x[0]=j;y[0]=i;
            }else{
                  fld[j][i]=true;
                  x[c-'0']=j;
                  y[c-'0']=i;
                  fin=max(fin,c-'0');
            }
      }
      int ans=0;
      REP(i,fin){
            int d[1000][1000];
            memset(d,-1,sizeof(d));
            queue<A> Q;
            Q.push((A){x[i],y[i],0});
            while(!Q.empty()){
                  A a=Q.front();Q.pop();
                  int xx=a.x,yy=a.y,cost=a.cost;
                  d[xx][yy]=cost;
//                  cout<<xx<<" "<<yy<<endl;
                  if(xx==x[i+1]&&yy==y[i+1]){
                        ans+=cost;
                        break;
                  }
                  REP(j,4){
                        int nx=xx+dx[j],ny=yy+dy[j];
                        if(nx<0||nx>=w||ny<0||ny>=h||!fld[nx][ny])continue;
                        if(d[nx][ny]!=-1)continue;
                        Q.push((A){nx,ny,cost+1});
                  }
            }
      }
      cout<<ans<<endl;
}

C++: #include<iostream>
#include<cstdio>
#include<string>
using namespace std;
int H,W,N;
const int MAX_H=1000;
const int MAX_W=1000;
string S[MAX_H];
int ans=0;
int X[10],Y[10];
int D[MAX_W][MAX_H];
int cou;
int dx[4]={-1,0,0,1};
int dy[4]={0,-1,1,0};
int xs,ys,xg,yg;
int E[MAX_W][MAX_H];
int solve(){
	cou=0;
	while(D[xg][yg]==-1){
		for(int i=0;i<H;i++){
			for(int j=0;j<W;j++){
				E[j][i]=D[j][i];
			}
		}
		for(int i=0;i<H;i++){
			for(int j=0;j<W;j++){
				if(D[j][i]==cou){
					for(int k=0;k<4;k++){
						if(j+dx[k]>=0&&j+dx[k]<W&&i+dy[k]>=0&&i+dy[k]<H){
							if(D[j+dx[k]][i+dy[k]]==-1&&S[i+dy[k]][j+dx[k]]!='X'){
								E[j+dx[k]][i+dy[k]]=cou+1;
							}
						}
					}
				}
			}
		}
		for(int i=0;i<H;i++)for(int j=0;j<W;j++)D[j][i]=E[j][i];
		cou++;
		printf("%d\n",cou);
	    }
	return D[xg][yg];
}

int main()
{
	scanf("%d%d%d",&H,&W,&N);
	for(int i=0;i<H;i++)cin >> S[i];
	for(int i=0;i<W;i++){
		for(int j=0;j<H;j++){
			if(S[j][i]!='X'&&S[j][i]!='.'){
				if(S[j][i]=='S'){
					X[0]=i;Y[0]=j;
				}
				else{
					X[S[j][i]-'0']=i;
					Y[S[j][i]-'0']=j;
				}
			}
		}
	}
	for(int ti=0;ti<N;ti++){
		for(int i=0;i<W;i++){
		    for(int j=0;j<H;j++){
			    D[i][j]=-1;
		    }
	    }
		xs=X[ti];
		ys=Y[ti];
		xg=X[ti+1];
		yg=Y[ti+1];
		D[xs][ys]=0;
		ans+=solve();
	}
	printf("%d\n",ans);
	return 0;
}