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 <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cfloat>
#include <map>
#include <utility>
#include <set>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
#include <sstream>
#include <complex>
#include <stack>
#include <queue>
#include <cstring>
#include <sstream>
#include <cassert>
using namespace std;
static const double EPS = 1e-10;
typedef long long ll;
typedef pair<int,int> PI;
#define rep(i,n) for(int i=0;i<(int)n;++i)
#define FOR(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i)
#define ALL(c) (c).begin(), (c).end()
#define mp(a,b) make_pair(a,b)
#define pb(a) push_back(a)
int dx[]={0,1,0,-1},dy[]={1,0,-1,0};

typedef struct{
  int x,y;
  int cost;
  int ch;
}mouse;

int maxch[100][100];

main(){
  int h,w,n;
  cin>>h>>w>>n;
  char ku[h][w];
  rep(i,h)cin>>ku[i];

  int sx,sy;
  rep(i,h)rep(j,w)if(ku[i][j]=='S')sx=i,sy=j;

  queue<mouse> Q;
  set<pair<PI,int> > app;
  Q.push((mouse){sx,sy,0,0});
  app.insert(mp(mp(sx,sy),0));

  int ans=0;
  while(!Q.empty()){
    //    cout<<Q.size()<<endl;
    mouse t=Q.front();Q.pop();
    int cx=t.x,cy=t.y,cost=t.cost;
    int ch=t.ch;
    if(ch==n){
      ans=cost;
      break;
    }



    rep(i,4){
      int nx=cx+dx[i],ny=cy+dy[i];
      if(nx<0 || nx>=h || ny<0 || ny>=w)continue;
	 if(ku[nx][ny]=='X')continue;
	 int nch=ch;
	 if(ku[nx][ny]<='9' && ku[nx][ny]>='1'){
	   int num=ku[nx][ny]-'0';
	   if(num==t.ch+1){
	     nch=ch+1;
	   }
	 }
	 if(maxch[nx][ny]>nch)continue;
	 maxch[nx][ny]=nch;
	 if(app.count(mp(mp(nx,ny),nch)))continue;
	 Q.push((mouse){nx,ny,cost+1,nch});
	 app.insert(mp(mp(nx,ny),nch));
    }
  }
  cout<<ans<<endl;
}

C++: #include <algorithm>
#include <bitset>
#include <cmath>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <string>
#include <utility>
using namespace std;

#define ABS(a) (((a) >= 0) ? (a) : -(a))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define MIN(a, b) ((a) > (b) ? (b) : (a))
#define FOR(i, a, b) for (int i = a; i < b; ++i)
#define RFOR(i, a, b) for (int i = a; i > b; --i)
#define REP(i, n) for (int i = 0; i < n; ++i)
#define int long long

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

const int kMaxH = 1000;
const int kMaxW = 1000;
const int kInf = 1000000000;

int H, W, N;
string maze[kMaxH];
int ans = 0;

int d[kMaxH][kMaxW];
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, -1, 0, 1};

int Bfs(char s, char g) {
  int sx, sy, gx, gy;
  REP(i, H) {
    REP(j, W) {
      if (maze[i][j] == s) { sx = i; sy = j; }
      if (maze[i][j] == g) { gx = i; gy = j; }
    }
  }

  queue<Pair> que;
  REP(i, H) { REP(j, W) { d[i][j] = kInf; } }
  que.push(Pair(sx, sy));
  d[sx][sy] = 0;

  while (que.size()) {
    Pair p = que.front(); que.pop();
    int x = p.first; int y = p.second;
    if (x == gx && y == gy) { break; }
    REP(i, 4) {
      int nx = x+dx[i]; int ny = y+dy[i];
      if (0 <= nx && nx < H && 0 <= ny && ny < W) {
        if (maze[nx][ny] != 'X' && d[nx][ny] == kInf) {
          que.push(Pair(nx, ny));
          d[nx][ny] = d[x][y]+1;
        }
      }
    }
  }

  return d[gx][gy];
}

signed main() {
  cin >> H >> W >> N;
  REP(i, H) { cin >> maze[i]; }

  ans += Bfs('S', '1');
  REP(i, N-1) { ans += Bfs('1'+i, '2'+i); }

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

C++: #include<stdio.h>
#include<stdlib.h>
#include<queue>
#include<algorithm>
#define INF 1000000
using namespace std;
typedef pair<int,int> P;
int dx[4]={-1,0,1,0};
int dy[4]={0,1,0,-1};
bool map[1000][1000];
int x[10],y[10];
int ans=0;
int h,w,n;

int search(int n){
    int d[1000][1000];
    std::fill(d,d+sizeof(d),INF);
    int sx=x[n],sy=y[n];
    int tx=x[n+1],ty=y[n+1];
    queue<P> q;
    q.push(P(sx,sy));
    d[sx][sy]=0;
    while(1){
        P p=q.front();
        q.pop();
        sx=p.first,sy=p.second;
        if(sx==tx&&sy==ty) return d[tx][ty];
        for(int i=0;i<4;i++){
            int X=sx+dx[i];
            int Y=sy+dy[i];
            if(map[X][Y]&&X>=0&&X<h&&Y>=0&&Y<w){
                q.push(P(X,Y));
                d[X][Y]=d[sx][sy]+1;
            }
        }
    }
}
int main(){
    for(int i=0;i<h;i++){
        for(int j=0;j<w;j++){
            char c=getchar();
            if(c!='x'){
                map[i][j]=true;
                if(c=='S'){
                    x[0]=i,y[0]=j;
                }else{
                    int k=atoi(&c);
                    x[k]=i;
                    y[k]=j;
                }
            }
        }
        getchar();
    }
    for(int i=0;i<n;i++){
        ans+=search(i);
    }
    printf("%d\n",ans);
}

C++: #include <iostream>
#include <stdio.h>
#include <queue>


#define REP(i,a,b) for(int i=a;i<b;i++)
#define rep(i,n) REP(i,0,n)

#define HMAX 1000
#define WMAX 1000
#define NMAX 9
#define INF 100000000
#define EMPTY -1
#define OBSTACLE -2

int H, W, N;
int map[HMAX + 2][WMAX + 2];

int dirs_h[] = {0, 0, 1, -1};
int dirs_w[] = {1, -1, 0, 0};

int factory[NMAX + 1][2];

using namespace std;

int go(int sh, int sw, int eh, int ew) {
	queue<int> q_h;
	queue<int> q_w;
	q_h.push(sh);
	q_w.push(sw);

	int cost[HMAX][WMAX];
	rep(i, HMAX)
		rep(j, WMAX)
			cost[i][j] = INF;
	cost[sh][sw] = 0;
	int min = 0;
	while (!q_h.empty()) {
		int p_h = q_h.front();
		int p_w = q_w.front();

		q_h.pop();
		q_w.pop();
		
		rep(i, 4){
			int pn_h = p_h + dirs_h[i];
			int pn_w = p_w + dirs_w[i];

			if (map[pn_h][pn_w] != OBSTACLE) {
				if (map[pn_h][pn_w] == EMPTY && cost[pn_h][pn_w] == INF) {
					q_h.push(pn_h);
					q_w.push(pn_w);
				}else{
					if (min > cost[pn_h][pn_w] + 1)
						min = cost[pn_h][pn_w] + 1;
				}
			}
		}
		cost[p_h][p_w] = min;
		min = INF;
		if (p_h == eh && p_w == ew)
			break;
	}
	int ans = cost[eh][ew];
	return ans;
}

int main() {
	scanf("%d%d%d", &H, &W, &N);
	
	rep(i, H){
		rep(j, W){
			char m;
			scanf(" %c",&m);
			int m_i = m - '0';
			switch (m) {
				case 'S':
					factory[0][0] = i + 1;
					factory[0][1] = j + 1;
					map[i + 1][j + 1] = EMPTY;
				break;
				case 'X':
					map[i + 1][j + 1] = OBSTACLE;
				break;
				case '.':
					map[i + 1][j + 1] = EMPTY;
				break;
				default:
					int num = m - '0';
					factory[num][0] = i + 1;
					factory[num][1] = j + 1;
					map[i + 1][j + 1] = EMPTY;
				break;
			}
		}
	}

	rep(i, H + 2){
		map[i][0] = OBSTACLE;
		map[i][W + 1] = OBSTACLE;
	}

	rep(j, W + 2){
		map[0][j] = OBSTACLE;
		map[H + 1][j] = OBSTACLE;
	}

	int sum = 0;
	rep(i, N) {
		sum += go(
			factory[i][0], factory[i][1],
			factory[i + 1][0], factory[i + 1][1]);
	}

	cout << sum << endl;
}