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 <algorithm>
#include <string>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <set>
#include <map>
#include <vector>
#include <queue>
#include <stack>
#include <functional>

#define sz(v) v.size()
#define pb(e) push_back(e)
#define mp(x, y) make_pair(x, y)
#define fst first
#define scd second
#define X first
#define Y second

using namespace std;

typedef long long ll;
typedef pair<int, int> pii;

const int MAX = 1000;
const int INF = MAX * MAX + MAX;

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

int hyo[MAX][MAX];
pii pt[10];

bool bfs(int h, int w, int s, int e, int low)
{
	queue<pii> Q;
	pii end = pt[e];
	
	Q.push(pt[s]);
	
	while (!Q.empty())
	{
		pii t = Q.front(); Q.pop();
		for (int d = 0; d < 4; ++d)
		{
			int mx = t.X + dx[d];
			int my = t.Y + dy[d];
			if (0 > mx || mx >= w || 0 > my || my >= h || hyo[my][mx] == -1) continue;
			if (hyo[my][mx] <= low || hyo[my][mx] > hyo[t.Y][t.X] + 1)
			{
				hyo[my][mx] = hyo[t.Y][t.X] + 1;
				Q.push(mp(mx, my));
				if (end.X == mx && end.Y == my) return true;
			}
		}
	}
	return false;
}

int main ( void )
{
	int h, w, n;
	
	while (cin >> h >> w >> n)
	{
		for (int y = 0; y < h; ++y)
		{
			for (int x = 0; x < w; ++x)
			{
				char c;
				
				cin >> c;
				
				switch (c)
				{
					case '.':
						hyo[y][x] = INF;
						break;
					case 'X':
						hyo[y][x] = -1;
						break;
					case 'S':
						hyo[y][x] = 0;
						pt[0] = mp(x, y);
						break;
					default: // 1 ~ 9
						hyo[y][x] = INF;
						pt[c-'0'] = mp(x, y);
						break;
				}
			}
		}
		
		for (int i = 0; i < n; ++i)
		{
			pii t = pt[i];
			bfs(h, w, i, i+1, hyo[t.Y][t.X]);
		}
		
		pii t = pt[n];
		cout << hyo[t.Y][t.X] << endl;
	}
	return 0;
}

C++: #include <stdio.h>  
#include <string.h>  
#include <queue>  
#define W 1003 
#define H 1003 
#define N 9  
int d[H][W];   
using namespace std;  
char m[H][W + 1];  
int w, h, n;  
int gx[N + 1], gy[N + 1];  
int dx[] = {0, 0, 1, -1}, dy[] = {1, -1, 0, 0};  
int bfs(int sx, int sy, int gx, int gy)  
{   
    queue<int> que;  
    que.push(sx * w + sy);  
    d[sx][sy] = 0;  
    while(que.size())  
    {  
        int x = que.front()/w, y = que.front()%w;  
        que.pop();  
        if(x == gx && y == gy)  
            break;  
  
        for(int di = 0; di < 4; ++di){  
            int nx = x + dx[di], ny = y + dy[di];  
            if(nx >= 0 && nx < h && ny >= 0 && ny < w && 'X' != m[nx][ny] && -1 == d[nx][ny]){  
                d[nx][ny] = d[x][y] + 1;  
                que.push(nx * w + ny);  
            }  
        }  
    }  
    return d[gx][gy];  
}  
void s()  
{  
    int ans = 0;  
    for(int i = 0; i < n; i ++)  
        ans = ans + bfs(gx[i], gy[i], gx[i + 1], gy[i + 1]);  
    printf("%d\n", ans);  
}  
int main()  
{ 
	memset(d, -1, sizeof(d));
    scanf("%d%d%d", &h, &w, &n);  
    for(int i = 0; i < h; i ++)  
        scanf("%s", m[i]);  
    for(int i = 0; i < h; i ++)  
        for(int j = 0; j < w; j ++){  
            if('1' <= m[i][j] && '9' >= m[i][j])  
                gx[m[i][j] - '0'] = i, gy[m[i][j] - '0'] = j;  
            else if('S' == m[i][j])  
                gx[0] = i, gy[0] = j;  
        }  
    if(w>=0|| h>=0)  
        s();  
    return 0;  
}

C++: #include<iostream>
#include<queue>
#include<string.h>
using namespace std;
int  cheese[1001][1001];
int  check[1001][1001];
char num[11]={'0','1','2','3','4','5','6','7','8','9'};
int q[4]={0,1,0,-1};
int p[4]={1,0,-1,0};
struct ST {
	int a;
	int b;
	int c;
	int d;
};
int main(){
	memset(cheese,0,sizeof(cheese));
	memset(check,0,sizeof(check));
	int h,w,n;
	int i,j,m;
	int ys,xs;
	char data;
	queue <ST> Q;
	ST x;
	ST y;
	cin>>h>>w>>n;//??¢??????????????°
	for(i=1;i<=h;i++){
		for(j=1;j<=w;j++){
			cin>>data;
			if(data=='S'){//????????????
				ys=i;//??????????????§?¨?
				xs=j;
			}
			else if(data=='X'){//?????????
				cheese[i][j]=-1;
			}
			else if(data!='.'){
				for(m=1;m<=9;m++){
					if(num[m]==data){
						cheese[i][j]=m;
					}
				}
			}
			
		}
	}
	x.a=ys;
	x.b=xs;
	x.c=0;
	x.d=1;
	Q.push(x);
	while(!Q.empty()){
		y=Q.front();
		Q.pop();
		check[y.a][y.b]=1;
		if(-1==cheese[y.a][y.b]){
			continue;
		}
		if(y.d==cheese[y.a][y.b]){
			if(n==y.d) break;
			memset(check,0,sizeof(check));
			while(!Q.empty()){
				Q.pop();
			}
			y.d+=1;
			x.a=y.a;
			x.b=y.b;
			x.c=y.c;
			x.d=y.d;
			Q.push(x);
			continue;
		}
		for(i=0;i<4;i++){
			if(y.a+q[i]>0&&y.a+q[i]<=h&&y.b+p[i]>0&&y.b+p[i]<=w&&check[y.a+q[i]][y.b+p[i]]!=1){
				x.a=y.a+q[i];
				x.b=y.b+p[i];
				x.c=y.c+1;
				x.d=y.d;
				Q.push(x);
			}
		}
	}
	cout<<y.c<<endl;
	return 0;
}

C++: // AOJ 0558
#include<iostream>
#include<string>
#include<map>
#include<queue>
#include<set>
#include<vector>
#define REP(i,n) for(int i=0;i<(int)(n);i++)
using namespace std;

typedef pair<int,int> P;

const int HMAX = 1008, WMAX = 1008;
char city[HMAX][WMAX];
int H, W, N;

P search(char c) {
  REP(y,H) REP(x,W) {
    if (city[x][y] == c) {
      return make_pair(x,y);
    }
  }
}


bool legal(int x, int y) {
  return 0 <= x and x < W and 0 <= y and y <= H;
}

typedef pair<int,P> Dat;

int distance(char start, char goal) {
  P startp = search(start), goalp = search(goal);
  priority_queue<Dat,vector<Dat>,greater<Dat> > q;
  set<P> s;
  q.push(Dat(0,startp));
  s.insert(startp);
  while (!q.empty()) {
    Dat d = q.top(); q.pop();
    P p = d.second;
    if (p == goalp) return d.first;
    int dx[4] = {0,1,0,-1}, dy[4] = {1,0,-1,0};
    REP(i, 4) {
      int nx = p.first + dx[i], ny = p.second + dy[i];
      P np = P(nx,ny);
      if (legal(nx,ny) and city[nx][ny] != 'X' 
          and s.find(np) == s.end()) {
        q.push(Dat(d.first + 1, np));
        s.insert(np);
      }
    }
  }
  throw 1;
}

int solve() {
  char current = 'S';
  int ans = 0;
  for (int i = 1; i <= N; i++) {
    ans += distance(current, '0' + i);
    current = '0' + i;
  }
  return ans;
}

int main() {
  cin >> H >> W >> N;
  REP(y, H) {
    string row;
    cin >> row;
    REP(x, W) {
      city[x][y] = row[x];
    }
  }

  cout << solve() << endl;
}