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 <cmath>
#include <queue>
#include <cstdio>
#include <cstring>
#include <algorithm>

#define INF 0x7f7f7f7f
#define PI acos(-1.0)

#define L(x)    (x) << 1
#define R(x)    (x) << 1 | 1
#define lowbit(x)   (x)&(-x)
#define Mid(l, r)   (l + r) >> 1
#define Min(x, y)   (x) < (y) ? (x) : (y)
#define Max(x, y)   (x) < (y) ? (y) : (x)
#define iabs(x)     (x) < 0 ? -(x) : (x)
#define CLR(arr, val)    memset(arr, val, sizeof(arr))

using namespace std;

char map[1024][1024];
int cur, h, w;
bool vis[1024][1024];

struct node {
	int x, y, step;
} sta, now, nex;

bool check(int x, int y) {
	if (x >= 0 && x < h && y >= 0 && y < w && !vis[x][y] && map[x][y] != 'X')	return true;
	return false;
}
int dir[4][2] = {1, 0, -1, 0, 0, 1, 0, -1};

node bfs(node s) {
	queue<node> q;
	q.push(s);
	while (!q.empty()) {
		now = q.front();
		q.pop();
		vis[now.x][now.y] = true;
		node next;
		next.step = now.step + 1;
		for (int i = 0; i < 4; i++) {
			next.x = now.x + dir[i][0];
			next.y = now.y + dir[i][1];

			if (check(next.x, next.y)) {
				if (map[next.x][next.y] == cur + '0') {
					map[next.x][next.y] = '.';
					return next;
				}
				q.push(next);
			}
		}
	}
}

int main() {
	int n, sx, sy;
	while (~scanf("%d%d%d", &h, &w, &n)) {
//		memset(map, 0, sizeof(map));
		int num = 1;
		for (int i = 0; i < h; i++) {
			for (int j = 0; j < w; j++) {
				cin >> map[i][j];
				if (map[i][j] == 'S')	sta.x = i, sta.y = j, map[i][j] = '.';
				else if (map[i][j] >= '0' && map[i][j] <= '9')	num = max(num, map[i][j] - '0');
			}
		}
//		cout << num << endl; 
		sta.step = 0;
		for (cur = 1; cur <= num; cur++) {
			memset(vis, 0, sizeof(vis));
			nex = bfs(sta);
			sta = nex;
//			cout << cur << ' ' << sta.step << endl;
		}
		cout << sta.step << endl;
	}
	return 0;
}

C++: #include<iostream>
#include<queue>
#define MAX 1000

typedef std::pair<int,int> P;

int h,w,N,PX[4]={1,-1,0,0},PY[4]={0,0,1,-1},sum=0;
char ch[MAX][MAX];

void bfs(P p,P q){
	std::queue<P> Q;
	Q.push(p);
	while(!Q.empty()){
		P u=Q.front();Q.pop();
		for(int i=0;i<4;++i){
			if(u.first+PX[i]>=0&&u.first+PX[i]<h&&u.second+PY[i]<w&&u.second+PY[i]>=0&&ch[u.first+PX[i]][u.second+PY[i]]!='X'){
				if(P(u.first+PX[i],u.second+PY[i])==q)
					return;
				else{
					++sum;
					Q.push(P(u.first+PX[i],u.second+PY[i]));
				}
			}
		}
	}
}

void solve(){
	int n=1;
	P s,p[10];
	for(int i=0;i<h;++i){
		for(int j=0;j<w;++j){
			if(ch[i][j]=='S')
				s.first=i;s.second=j;
			if(ch[i][j]==char(n)){
				p[n]=P(i,j);
				++n;
			}
		}
	}
	bfs(s,p[1]);
	for(int i=1;i<9;++i){
		bfs(p[i],p[i+1]);
	}
}

int main(){
	std::cin>>h>>w>>N;
	for(int i=0;i<h;++i){
		for(int j=0;j<w;++j){
			std::cin>>ch[i][j];
		}
	}
	solve();
	std::cout<<sum<<std::endl;
	return 0;
}

C++: #include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
const int INF = 1000000000;
#define REP(i,s,n) for(int i=(int)(s);i<(int)(n);i++)
#define rep(i,n) REP(i, 0, n)
typedef pair <int, int> P;
const int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};
char f[1001][1001];
int vd[1001][1001];
int esax[10], esay[10];
int h, w, n;
int bfs(int sx, int sy, int gx, int gy){
    rep(i, h + 1) rep(j, w + 1) vd[i][j] = INF;
    queue <P> opt;
    opt.push(P(sx, sy));
    vd[sx][sy] = 0;
    
    while(opt.size()){
        P p = opt.front(); opt.pop();
        if(p.first == gx && p.second == gy) break;
        rep(i, 4){
            int nx = p.first + dx[i], ny = p.second + dy[i];
            if(0 <= nx && 0 <= ny && vd[nx][ny] == INF && f[nx][ny] != 'X'){
                opt.push(P(nx, ny));
                vd[nx][ny] = vd[p.first][p.second] + 1;
            }
        }
    }
    //cout << vd[gx][gy] << endl;;
    return vd[gx][gy];
}
int main(){
    cin >> h >> w >> n;
    rep(i, h) rep(j, w){
        cin >> f[i][j];
        if(f[i][j] == 'S')
          esax[0] = i, esay[0] = j;
        if('1' <= f[i][j] && f[i][j] <= '9'){
            int num = f[i][j] - '0';
            esax[num] = i, esay[num] = j;
        }
    }
    rep(j, w) f[h + 1][j] = 'X';
    rep(i, h) f[w + 1][i] = 'X';
    int ans = 0;
    rep(i, n)
      ans += bfs(esax[i], esay[i], esax[i + 1], esay[i + 1]);
    cout << ans << endl;
    return 0;
}

C++: #include<vector>
#include<list>
#include<algorithm>
#include<iostream>
#include<string>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
using namespace std;
void f(int a[][1002],int b[][1002],int p,int q,int d,int e,int m){
  if(a[p][q]==-1);
  else if(p==d&&q==e){
    if(b[p][q]==-1||b[p][q]>m)
      b[p][q]=m;
  }else if(b[p][q]==-1||b[p][q]>m){
    b[p][q]=m;
    f(a,b,p-1,q,d,e,m+1);
    f(a,b,p,q-1,d,e,m+1);
    f(a,b,p+1,q,d,e,m+1);
    f(a,b,p,q+1,d,e,m+1);
  }
  return;
}
void g(int a[][1002],int b[][1002],int p,int q,int d,int e,int m){
  if(a[p][q]==-1);
  else if(p==d&&q==e){
    if(b[p][q]==-1||b[p][q]>m)
      b[p][q]=m;
  }else if(b[p][q]==-1||b[p][q]>m){
    b[p][q]=m;
    if(d-p)
      g(a,b,p+(d-p>0?1:-1),q,d,e,m+1);
    if(e-q)
      g(a,b,p,q+(e-q>0?1:-1),d,e,m+1);
  }
  return;
}
int main(){
  int i,j;
  int a[1002][1002],b[1002][1002],c[10],d[10],w,h,n;
  int sm=0;
  memset(a,-1,sizeof(a));
  cin>>h>>w>>n;
  for(i=0;i<h;i++){
    string s;
    cin>>s;
    for(j=0;j<w;j++){
      if(s[j]=='X');
      else{
	a[j+1][i+1]=0;
	if(s[j]=='.');
	else if(s[j]=='S'){
	  c[0]=j+1;
	  d[0]=i+1;
	}else{
	  c[s[j]-'0']=j+1;
	  d[s[j]-'0']=i+1;
	}
      }
    }
  }
  for(i=0;i<n;i++){
    memset(b,-1,sizeof(b));
    g(a,b,c[i],d[i],c[i+1],d[i+1],0);
    if(b[c[i+1]][d[i+1]]==-1){
      memset(b,-1,sizeof(b));
      f(a,b,c[i],d[i],c[i+1],d[i+1],0);
    }    
    sm+=b[c[i+1]][d[i+1]];
  }
  cout<<sm<<endl;
  return 0;
}