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<vector>
#include<algorithm>
#include<string>
#include<queue>

#define mp make_pair
#define f first
#define s second

using namespace std;

typedef pair<int,int> P;

const int dx[4]={1,0,-1,0},dy[4]={0,1,0,-1};
int h,w;
string grid[1000];
int d[1000][1000];

void bfs(P S){

  queue<P>que;
  que.push(S);
  d[S.f][S.s]=0;

  while(!que.empty()){
    P now=que.front();
    
    que.pop();
    for(int i=0;i<4;i++){
      if(0<=now.f+dx[i] && 0<=now.s+dy[i] &&
	 now.f+dx[i]<h && now.s+dy[i]<w
	 && grid[now.f+dx[i]][now.s+dy[i]]!='X'){

	if(d[now.f][now.s]+1<d[now.f+dx[i]][now.s+dy[i]]){
	  d[now.f+dx[i]][now.s+dy[i]]=d[now.f][now.s]+1;
	  que.push(P(now.f+dx[i],now.s+dy[i]));
	}
      }
    }
  }
}

int main(void){
  int n;
  P v[1001];

  cin >> h >> w >> n;

  for(int i=0;i<h;i++)cin >> grid[i];

  for(int i=0;i<h;i++){
    for(int j=0;j<w;j++){
      if(grid[i][j]=='S')v[0]=mp(i,j);
      if(grid[i][j]!='X'&&grid[i][j]!='.')
	v[grid[i][j]-'0']=mp(i,j);
    }
  }

  int ans=0;
  for(int i=0;i<n;i++){
    for(int j=0;j<h;j++)
      for(int k=0;k<w;k++)d[j][k]=100000000;
    bfs(v[i]);
    ans+=d[v[i+1].f][v[i+1].s];
  }

  cout << ans << endl;

  return 0;
}

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

char JOI[MAX][MAX];
int h,w,n;
int dx[]={0,-1,0,1};
int dy[]={1,0,-1,0};

pair<int, int> goal[10];
bool check(int a,int b){
    return (a>=1&&a<=h&&b>=1&&b<=w);
}

int step[MAX][MAX];
int bfs(pair<int, int> st,pair<int, int> en){
    queue<pair<int,int> > q;
    q.push(st);
    memset(step, -1, sizeof(step));
    step[st.first][st.second]=0;
    int stp=0;
    while(!q.empty()){
        pair<int, int> S=q.front(); q.pop();
        int x=S.first;  int y=S.second;
        stp=step[x][y];
        for(int i=0; i<4; i++){
            int cx=x+dx[i]; int cy=y+dy[i];
            if(check(cx, cy)){
                if(JOI[cx][cy]!='X'&&step[cx][cy]==-1){
                    if(cx==en.first&&cy==en.second) return stp+1;
                    q.push(make_pair(cx, cy));
                    step[cx][cy]=stp+1;
                }
            }
        }
    }
    return stp;
}
int main(){
    cin>>h>>w>>n;
    for(int i=1; i<=h; i++){
        for(int j=1; j<=w; j++){
            cin>>JOI[i][j];
            if(JOI[i][j]=='S') goal[0]=make_pair(i, j);
            else if(JOI[i][j]>='0'&&JOI[i][j]<='9'){
                int x=JOI[i][j]-'0';
                goal[x]=make_pair(i, j);
            }
        }
    }
    int ans=0;
    for(int i=0; i<n; i++){
        ans+=bfs(goal[i],goal[i+1]);
    }
    cout<<ans<<endl;
}

C++: #include<stdio.h>
#include<queue>
#include<string.h>
using namespace std;
int h,w,n,flag[1005][1005];
char map[1005][1005];
struct point
{
	int x;
	int y;
	int t;
}chess[15];
int bfs(struct point be,struct point end)
{
	point temp,emp;
	queue<point>q;
	q.push(be);
	memset(flag,0,sizeof(flag));
	while(!q.empty())
	{
		temp=q.front();
		q.pop();
		flag[temp.x][temp.y]=1;
		for(int i=-1;i<2;i++)
			for(int j=-1;j<2;j++)
				if(i!=j&&i!=-j)
				{
					emp.x=temp.x+i;
					emp.y=temp.y+j;
					emp.t=temp.t+1;
					if(emp.x<0||emp.x>=h||emp.y<0||emp.y>=w||flag[emp.x][emp.y]==1)
						continue;
					if(map[emp.x][emp.y]=='X')
						continue;
					if(emp.x==end.x&&emp.y==end.y)
						return emp.t;
					q.push(emp);
				}
	}
	return 0;
}
int main()
{
	while(scanf("%d%d%d",&h,&w,&n))
	{
		int sum=0;
		for(int i=0;i<h;i++)
			scanf("%s",map[i]);
		for(int i=0;i<h;i++)
			for(int j=0;j<w;j++)
			{
				int temp=map[i][j]-'0';
				if(map[i][j]=='S')
				{
					chess[0].x=i;
					chess[0].y=j;
					chess[0].t=0;
				}
				else if(temp>0&&temp<10)
				{
					chess[temp].x=i;
					chess[temp].y=j;
					chess[temp].t=0;
				}				
			}
			for(int i=0;i<n;i++)
				sum=sum+bfs(chess[i],chess[i+1]);
			printf("%d\n",sum);
	}
	return 0;
 }

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

#define pb(n) push_back(n)
#define fi first
#define se second
#define X real()
#define Y imag()
#define value(x,y,w,h) (x >= 0 && x < w && y >= 0 && y < h)
#define all(r) (r).begin(),(r).end()
#define gsort(st,en) sort((st),(en),greater<int>())
#define vmax(ary) *max_element(all(ary))
#define vmin(ary) *min_element(all(ary))
#define debug(x) cout<<#x<<": "<<x<<endl
#define fcout(n) cout<<fixed<<setprecision((n))
#define scout(n) cout<<setw(n)
#define vary(type,name,size,init) vector< type> name(size,init)

#define rep(i,n) for(int i = 0; i < (int)(n);++i)
#define REP(i,a,b) for(int i = (a);i < (int)(b);++i)
#define repi(it,array) for(auto it = array.begin(),end = array.end(); it != end;++it)
#define repa(n,array) for(auto &n :(array))

using ll = long long;
using vi = vector<int>;
using vl = vector<ll>;
using dict = map<string,int>;
using comd = complex<double>;
using pii = pair<int,int> ;

constexpr int imax = ((1<<30)-1)*2+1 ;
constexpr int inf = 10000000;
constexpr double PI = acos(-1.0) ;
double eps = 1e-10 ;
const int dy[] = {-1,0,1,0};
const int dx[] = {0,-1,0,1};

int N,W,H,S;
vector<vector<int>> maps;
int main(){
  cin.tie(0);
  ios::sync_with_stdio(false);
  char c;
  int n = 0;
  cin >> W >> H >> N;
  char area[H][W];
  maps = vector<vector<int>>(H,vector<int>(W,-1));
  pii pos;
  rep(i,W){
    rep(j,H){
      cin >> c ;
      area[j][i] = c;
      if(c == 'S'){
        pos = make_pair(j,i);
        ++n;
      }
    }
  }
  queue<pii> q;
  q.push(pos);
  maps[pos.fi][pos.se] = 0;
  n = 1;
  int ans = 0;
  while(!q.empty()){
    pii p = q.front();q.pop();
    rep(i,4){
      int x = p.fi + dx[i],y = p.se+dy[i];
      if(value(x,y,H,W)){
        if(area[x][y] - '0' == n){
          ans += maps[p.fi][p.se] + 1;
          maps = vector<vector<int>>(H,vector<int>(W,-1));
          maps[x][y] = 0;
          q = queue<pii>();
          q.push(make_pair(x,y));
          if(n == N){
            q.pop();
          }
          ++n;
          break;
        }
        else if(area[x][y] != 'X' && (maps[x][y] >= maps[p.fi][p.se]+1 || maps[x][y] == -1)){
          q.push(make_pair(x,y));
          maps[x][y] = maps[p.fi][p.se] +1 ;
        }
      }
    }
  }
  cout << ans << endl;
  return 0;
}