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>
using namespace std;

typedef pair<int,int> P;
#define FOR(i,a,b) for(int i=(a);i<(int)(b);i++)
#define rep(i,n) FOR(i,0,n)
#define F first
#define S second

const int M = 1024;
const int INF = 114514;
int h,w,n;
char f[M][M];
int d[M][M];
int dx[]={1,0,-1,0};
int dy[]={0,1,0,-1};
vector<P> cheese(12);

void init() {
    rep(y,M) rep(x,M) f[y][x] = '$';
    cheese.clear();
}

bool ng(int x, int y) {
    return (x<0 or w<=x or y<0 or h<=y);
}

int bfs(P s, P g) {
    int gx=g.F, gy=g.S;
    queue<P> Q;
    rep(y,M) rep(x,M) d[y][x] = INF;
    Q.push(s);
    d[s.S][s.F] = 0;

    while(Q.size()) {
        P p = Q.front(); Q.pop();
        if(p.F==gx and p.S==gy) break;

        rep(i,4) {
            int nx = p.F + dx[i], ny = p.S + dy[i];
            if(ng(nx,ny) or f[ny][nx]=='X' or d[ny][nx]<INF) continue;
            d[ny][nx] = d[p.S][p.F] + 1;
            Q.push(P(nx,ny));
        }
    }

    return d[gy][gx];
}

int main() {
    while(cin>>h>>w>>n) {
        init();
        rep(y,h) rep(x,w) {
            cin >> f[y][x];
            char c = f[y][x];
            if(c!='.' and c!='S' and c!='X') cheese[c-'0'] = make_pair(x,y);
            if(c == 'S') cheese[0] = make_pair(x,y);
        }

        int ans = 0;
        rep(i,n) ans += bfs(cheese[i], cheese[i+1]);
        cout << ans << endl;
    }

    return 0;
}

C++: #include<iostream>
#include<cstdio>
#include<string>
using namespace std;
int main()
{
	int h,w,n;
	string ss[1000];
	scanf("%d%d%d",&h,&w,&n);
	for(int i=0;i<h;i++)cin >> ss[i];
	int ans=0;

	int x[1000][1000];
	int X,Y;

	for(int i=1;i<=n;i++){
		for(int j=0;j<h;j++){
			for(int k=0;k<w;k++){
				if(i==1&&ss[j][k]=='S')x[j][k]=0;
				else if(i!=1&&ss[j][k]==(i-1)+'0')x[j][k]=0;
				else x[j][k]=30000;
				if(ss[j][k]==i+'0'){
					X=j;Y=k;
				}
			}
		}
		int N=0;
		while(x[X][Y]==30000){
			for(int j=0;j<h;j++){
				for(int k=0;k<w;k++){
					if(x[j][k]==N){
						if(j!=h-1&&ss[j+1][k]!='X')x[j+1][k]=min(x[j+1][k],x[j][k]+1);
						if(j!=0&&ss[j-1][k]!='X')x[j-1][k]=min(x[j-1][k],x[j][k]+1);
						if(k!=0&&ss[j][k-1]!='X')x[j][k-1]=min(x[j][k-1],x[j][k]+1);
						if(k!=w-1&&ss[j][k+1]!='X')x[j][k+1]=min(x[j][k+1],x[j][k]+1);
					}
				}
			}
			
			N++;
		}
		ans+=x[X][Y];
	}
	cout << ans << "\n";
	return 0;
}

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

int dx[] = {1, 0, -1, 0}, dy[] = {0, 1, 0, -1};
char field[1000][1000];
bool flg[1000][1000] = {{0}};

class Data {
   public:
    int x, y, count;
    Data() {}
    Data(int x, int y, int count) : x(x), y(y), count(count) {}
};
int main() {
    int h, w, n;
    cin >> h >> w >> n;
    Data start;
    int ans = 0;
    for (int i = 0; i < h; i++) {
        cin >> field[i];
        for (int j = 0; j < w; j++) {
            if (field[i][j] == 'S') {
                start = Data(j, i, 0);
            }
        }
    }
    for (int i = 1; i <= n; i++) {
        queue<Data> Q;
        Q.push(start);
        memset(flg, 0, sizeof(flg));
        while (!Q.empty()) {
            Data d = Q.front(); Q.pop();
            if (field[d.y][d.x] == i + '0') {
                start = Data(d.x, d.y, d.count);
                break;
            }
            if (flg[d.y][d.x]) continue;
            flg[d.y][d.x] = true;
            for (int j = 0; j < 4; j++) {
                int px = d.x + dx[j], py = d.y + dy[j];
                if (px < 0 || py < 0 || px >= w || py >= h) continue;
                if (field[py][px] == 'X') continue;
                Q.push(Data(px, py, d.count + 1));
            }
        }
        ans = start.count;
    }

    cout << ans << endl;
    return 0;
}

C++: #include <iostream>
#include <set>
#include <algorithm>
#include <queue>

using namespace std;

typedef pair<int ,int> P;
#define INF 10000000

int W, H, N;
char map[1010][1010];
int dir[4][2] = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
int d[1010][1010];
int G[10][2];

bool InBox(int x,int y)
{
  return x>=0 && x<W && y>=0 && y<H;
}

int bfs(int k)
{
  P set, goal;
  set.first = G[k][0];
  set.second = G[k][1];
  goal.first = G[k + 1][0];
  goal.second = G[k + 1][1];
  for (int i = 0; i < H; i++)
    for (int j = 0; j < W; j++)
      d[i][j] = INF;

  queue<P> que;
  que.push(P(G[k][0], G[k][1]));
  d[G[k][1]][G[k][0]] = 0;
  while (que.size())
  {
    P p = que.front();
    que.pop();
    
    if (p.first == G[k + 1][0] && p.second == G[k+ 1][1])
      return d[goal.second][goal.first];
    for (int i = 0; i < 4; i++)
    {
      int nx = p.first+dir[i][0];
      int ny = p.second+dir[i][1];

      if (InBox(nx,ny)&&map[ny][nx]!='X'&&d[ny][nx]==INF)
      {
        d[ny][nx] = d[p.second][p.first] +1;
        que.push(P(nx,ny));
        
      }
    }
  }
}

int main()
{
  cin >> H >> W >> N;
  for (int y = 0; y < H; y++)
    for (int x = 0; x < W; x++)
    {
      cin >> map[y][x];
      if (map[y][x] == 'S')
      {
        G[0][0] = x;
        G[0][1] = y;
      }
      else if (map[y][x] > '0' && map[y][x] <= '9')
      {
        G[map[y][x] - '0'][0] = x;
        G[map[y][x] - '0'][1] = y;
      }
    }
  int sum = 0;
  for (int i = 0; i < N; i++)
  {

    sum += bfs(i);
  }
  cout << sum << endl;
  return 0;
}

C++: #include<algorithm>
#include<iostream>
#include<queue>
#include<ctype.h>
#include<limits.h>

int h, w, n;
int sx, sy;
int gx, gy;
char map[1002][1002];
int d[1001][1001];
bool visited[1001][1001];
int dx[] = { 0, 1, 0, -1 }, dy[] = { -1, 0, 1, 0 };
int ans;

bool compare( const data &d1, const data &d2 )
{
	return d1.d > d2.d;
}

void bfs()
{
	d[sx][sy] = 0;
	visited[sx][sy] = true;
	std::queue<std::pair<int,int> > q;
	q.push( std::make_pair<int,int>( sx, sy ) );
	
	while( !q.empty() ){
		std::pair<int,int> p = q.front(); q.pop();
		int x = p.first;
		int y = p.second;
		
		for( int i = 0; i < 4; i++ ){
			int ix = x + dx[i];
			int iy = y + dy[i];
			
			if( ix >= 1 && ix <= w && iy >= 1 && iy <= h && map[ix][iy] != 'X' && !visited[ix][iy] ){
			 	d[ix][iy] = d[x][y] + 1;
				q.push( std::make_pair<int,int>( ix, iy ) );
				visited[ix][iy] = true;
			}
		}	
	}

	return;
}

int main()
{
	std::cin >> h >> w >> n;
	
	for( int i = 1; i <= h; i++ ){
	 	for( int j = 1; j <= w; j++ ){
			std::cin >> map[j][i];
			if( map[j][i] == 'S' ){
			 	sx = j;
				sy = i;
			}
		}
	}
	
	for( int k = 1; k <= n; k++ ){
		for( int i = 1; i <= h; i++ ){
		 	for( int j = 1; j <= w; j++ ){
			 	d[j][i] = INT_MAX / 4;
				visited[j][i] = false;
			}
		}	
		
		bfs();
		
		for( int i = 1; i <= h; i++ ){
		 	for( int j = 1; j <= w; j++ ){
				if( map[j][i] == k + '0' ){
				 	gx = j;
					gy = i;
				}
			}
		}
		
		ans += d[gx][gy];
		
		sx = gx;
		sy = gy;
	}
	
	std::cout << ans << std::endl;

	return 0;
}