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 <utility>
#include <queue>
using namespace std;

typedef pair<int, int> Pair;
const int INF = 100000000;

int H, W, N;

const int MAX_H = 1000, MAX_W = 1000;
char plant[MAX_H][MAX_W];
int sx, sy;
int dx[4] = {0,1,0,-1}, dy[4] = {1,0,-1,0};
int d[MAX_H][MAX_W];
int mytime;

void bfs() {
    queue<Pair> que;
    for (int i = 0; i < H; i++) {
        for (int j = 0; j < W; j++) {
            d[i][j] = INF;
        }
    }
    char muscle = '1';
    que.push(Pair(sx,sy));
    d[sx][sy] = 0;
    while (que.size()) {
        Pair p  = que.front(); que.pop();
        if (int(muscle)-48-1 == N) break;
        for (int i = 0; i < 4; i++) {
            int nx = p.first + dx[i], ny = p.second + dy[i];
            if (0 <= nx && nx < H && 0 <= ny && ny < W && plant[nx][ny] != 'X' && d[nx][ny] == INF) {
                que.push(Pair(nx, ny));
                d[nx][ny] = d[p.first][p.second] + 1;
            }
            if (muscle == plant[nx][ny]) {
                while(que.size()) {que.pop();}
                que.push(Pair(nx, ny));
                muscle = muscle + 1;
                mytime += d[nx][ny];
                for (int i = 0; i < H; i++) {
                    for (int j = 0; j < W; j++) {
                        d[i][j] = INF;
                    }
                }
                d[nx][ny] = 0;
                break;
            }
        }
    }
}

void solve() {
    mytime = 0;
    bfs();
    printf("%d\n", mytime);
}

int main () {
    //cin >> H >> W >> N;
    scanf("%d%d%d", &H, &W, &N);
    for (int i = 0; i < H; i++) {
        scanf("%s",plant[i]);
        for (int j = 0; j < W; j++) {
            if(plant[i][j] == 'S') {sx = i; sy = j;}
        }
    }
    solve();
}

C++: 10 10 9
.X...X.S.X
6..5X..X1X
...XXXX..X
X..9X...X.
8.X2X..X3X
...XX.X4..
XX....7X..
X..X..XX..
X...X.XX..
..X.......

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

int h, w, n;
const int MAX_N = 1005;
char map[MAX_N][MAX_N];
int visit[MAX_N][MAX_N];
struct point{
	int x, y;
	int step;
	point(){
		x = 0; y = 0; step = 0;
	}
	point(int xx, int yy, int ss){
		x = xx;
		y = yy;
		step = ss;
	}
};
struct point p[16];

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

int ok(int x, int y){
	if (x >= 0 && x<h && y >= 0 && y<w) return 1;
	return 0;
}

int bfs(int next){
	for (int i = 0; i<MAX_N; i++){
		for (int j = 0; j < MAX_N; j++){
			visit[i][j] = 0;
		}
	}
	int nextcheese = next + 1;

	queue<point> q;
	point cur(p[next].x, p[next].y, 0);
	q.push(cur);
	while (q.size()){
		cur = q.front(); q.pop();
		int x = cur.x, y = cur.y;
		int nx, ny;
		for (int i = 0; i<4; i++){
			nx = x + dx[i]; ny = y + dy[i];
			if (ok(nx, ny)){
				if ((map[nx][ny] - '0') == nextcheese) return ++cur.step;
				if ((map[nx][ny] == '.') && visit[nx][ny] == 0){
					q.push(point(nx, ny, cur.step + 1));
					visit[nx][ny] = 1;
				}
			}
		}
	}
}

void solve(){
	cin >> h >> w >> n;
	for (int i = 0; i<h; i++){
		for (int j = 0; j<w; j++){
			cin >> map[i][j];
		}
	}
	for (int i = 0; i<h; i++){
		for (int j = 0; j<w; j++){
			char ch = map[i][j];
			switch (ch){
			case '.': break;
			case 'X': break;
			case 'S': p[0].x = i; p[0].y = j; map[i][j] = '.'; break;
			default:
				int t = (ch - '0');
				p[t].x = i; p[t].y = j;
			}
			/* if(map[i][j]=='S'){
			p[0].x=i; p[0].y = j;
			map[i][j]='.';
			}
			else if(isdigit(map[i][j])){
			int index=map[i][j]-'0';
			p[index].x=i; p[index].y=j;
			}*/
		}
	}
	int step = 0;
	for (int i = 0; i<n; i++){
		step += bfs(i);
	}
	printf("%d\n", step);
}


int main(){
	solve();
}

C++: #include <iostream>
#include <queue>
#include <algorithm>
#define N 1002
#define INFINITY 2000000000
using namespace std;
void bfs();
int h,w,n,num[N][N],d[N*N],u,m,x=1;
string color[N*N],in[N*N];//????¬??????????????????????????????????
int main(){
  int i,j,k;
  cin >> h >> w >> n;
  for(i=0;i<h+2;i++)
    for(j=0;j<w+2;j++)
      num[i][j]=-1;
  for(i=1;i<=h;i++) cin >> in[i],in[i]='X'+in[i];
  k=0;
  for(i=1;i<=h;i++){
    for(j=1;j<=w;j++){
      if(in[i][j]!='X') num[i][j]=k,k++;
    }
  }
  bfs();
  return 0;
}
void bfs(){
  int i,j,p=1,t=0,flag=0;
  char start='S',goal='1';
  queue<int> q;
  while(1){
    if(flag==1) start=x+'0',goal=x+'0'+1,x++;
    if(x>n+1) break;
    for(i=1;i<=h;i++){
      for(j=1;j<=w;j++){
	color[num[i][j]]="WHITE",d[num[i][j]]=INFINITY;
      }
    }
    for(i=1;i<=h;i++){
      for(j=1;j<=w;j++){
	if(in[i][j]==start) color[num[i][j]]="GLAY",d[num[i][j]]=0,q.push(num[i][j]);
      }
    }
    while(q.empty()!=1){
      u=q.front();
      q.pop();
      for(i=1;i<=h;i++){
	for(j=1;j<=w;j++){
	  if(num[i][j]!=-1&&(num[i-1][j]==u||num[i+1][j]==u||num[i][j+1]==u||num[i][j-1]==u)&&color[num[i][j]]=="WHITE"){
	    color[num[i][j]]="GLAY";
	    d[num[i][j]]=d[u]+1;
	    q.push(num[i][j]);
	  }
	}
      }
      color[u]="BLACK";
    }
    for(i=1;i<=h;i++){
      for(j=1;j<=w;j++){
	if(in[i][j]==goal) t+=d[num[i][j]];
      }
    }
    flag=1;
  }
  cout << t << endl;
}

C++: #include<stdio.h>
#include<queue>
#include<map>
#define INF 10000000
using namespace std;
typedef pair<int,int> P;
bool pos[1000][1000];
int d[1000][1000];
int cx[10];
int cy[10];
int dx[4]={-1,0,0,1};
int dy[4]={0,1,-1,0};
int h,w,n;
int bfs(int sx,int sy,int gx,int gy){
	int i,j;
	queue<P> que;
	for(i=0;i<h;i++)for(j=0;j<w;j++)d[i][j]=INF;
	d[sx][sy]=0;
	que.push(P(sx,sy));
	while(!que.empty()){
		P p=que.front();
		que.pop();
		int x=p.first;
		int y=p.second;
		for(i=0;i<4;i++){
			if(x+dx[i]>=0&&x+dx[i]<h&&y+dy[i]>=0&&y+dy[i]<w&&pos[x+dx[i]][y+dy[i]]&&d[x+dx[i]][y+dy[i]]==INF){
				d[x+dx[i]][y+dy[i]]=d[x][y]+1;
				que.push(P(x+dx[i],y+dy[i]));
			}
		}
	}
	return d[gx][gy];
}
		
int main(){
	int i,j;
	char c;
	scanf("%d %d %d",&h,&w,&n);
	for(i=0;i<h;i++)for(j=0;j<w;j++)pos[i][j]=true;
	for(i=0;i<h;i++)for(j=0;j<w;j++){
		scanf(" %c",&c);
		if(c=='S'){cx[0]=i;cy[0]=j;}
		else if(c>='1'&&c<='9'){cx[c-'0']=i;cy[c-'0']=j;}
		else if(c=='X')pos[i][j]=false;
	}
	int ans=0;
	for(i=1;i<=n;i++)ans+=bfs(cx[i-1],cy[i-1],cx[i],cy[i]);
	printf("%d",ans);
	return 0;
}