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<cstring>
#include<cctype>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<vector>
#include<stack>
#include<queue>
#include<set>
#include<map>
#include<bitset>
#include<utility>
#include<string>

using namespace std;

char ko[1005][1005];
int used[1005][1005];
int dx[4]={0,1,0,-1};
int dy[4]={-1,0,1,0};
int sx,sy;
int maxx,maxy;
int n;
int ans;

typedef struct{
  int x,y;
  int c;
}P;

int rat(int na);
int fatoi(char a);

main(){
  int i,j,temp; 
  cin >> maxy >> maxx;
  cin >> n;
  for(i=0;i<maxy;i++){
    for(j=0;j<maxx;j++){
      cin >> ko[j][i];
      if(ko[j][i]=='S'){
	sx=j;
	sy=i;
      }
    }
  }
  for(i=1;i<=n;i++) ans+=rat(i);
  cout << ans << endl;

}

int rat(int na){
  //  puts("B");
  memset(used,0,sizeof(used));
  queue<P> que;
  que.push((P){sx,sy,0});
  used[sx][sy]=1;
  while(que.size()>0){
    //  puts("C");
    P p=que.front();
    que.pop();
    //    cout << p.c << '_' << ko[p.x][p.y] << '_' << na << endl;
    if(fatoi(ko[p.x][p.y])==na){
      //      puts("A");
      sx=p.x;
      sy=p.y;
      //      cout << p.c << '_' << ko[p.x][p.y] << '_' << na << endl;
      return(p.c);
    }
    for(int i=0;i<4;i++){
      int mx=p.x+dx[i];
      int my=p.y+dy[i];
      if(0<=mx && mx < maxx && 0<=my && my<maxy){
	if(ko[mx][my]!='X' && used[mx][my]!=1){
	  used[mx][my]=1;
	  que.push((P){mx,my,p.c+1});
	}
      }
    }
  }
  return (-1);
}

int fatoi(char a){
  if(a=='0') return 0;
  if(a=='1') return 1;
  if(a=='2') return 2;
  if(a=='3') return 3;
  if(a=='4') return 4;
  if(a=='5') return 5;
  if(a=='6') return 6;
  if(a=='7') return 7;
  if(a=='8') return 8;
  if(a=='9') return 9;
  return -1;
}

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

#define INF 10000000

typedef pair<int,int> P;

queue<P> que;
char map[1000][1001];
int vst[1000][1000];
int dx[4]={1,0,-1,0},dy[4]={0,1,0,-1};
int H,W,N,sx,sy,sum=0;

int main() {
	scanf("%d %d %d",&H,&W,&N);
	for(int i=0;i<H;i++) {
		scanf("%s",map[i]);
		char *ptr=strchr(map[i],'S');
		if(ptr!=NULL) sx=ptr-map[i],sy=i;
	}
	que.push(P(sx,sy));
	for(int i=1;i<=N;i++) {
		for(int j=0;j<H;j++) {
			for(int k=0;k<W;k++) {
				vst[j][k]=INF;
			}
		}
		vst[sy][sx]=0;
		while(!que.empty()) {
			P p=que.front();
			que.pop();
			if(map[p.second][p.first]==i+'0') {
				sum+=vst[p.second][p.first];
				while(!que.empty()) que.pop();
				que.push(P(p.first,p.second));
				sx=p.first,sy=p.second;
				break;
			}
			for(int j=0;j<4;j++) {
				int nx=p.first+dx[j],ny=p.second+dy[j];
				if(0<=nx&&nx<W&&0<=ny&&ny<H&&map[ny][nx]!='X'&&vst[ny][nx]==INF) {
					vst[ny][nx]=vst[p.second][p.first]+1;
					que.push(P(nx,ny));
				}
			}
		}
	}
	printf("%d\n",sum);
	return 0;
}

C++: #include<bits/stdc++.h>
using namespace std;
struct ma
{
	int x;
	int y;
};
int dx[4] = { 0, 1, 0, -1 }, dy[4] = { 1, 0, -1, 0 };
char m[2200][2200];
int map[2200][2200];
int main()
{
	int ans = 0;
	int tate, yoko;
	int n;
	cin >> tate >> yoko >> n;
	
	ma sta;
	for (int i = 0; i < tate; i++)
	{
		for (int k = 0; k < yoko; k++)
		{
			cin >> m[i][k];
			if (m[i][k] == 'S')
			{
				sta.x = k;
				sta.y = i;
			}
		}
	}
	int HP = 1;
	queue<ma> hoge;
	for (int i = 0; i < n; i++)
	{
		hoge.push(sta);
		
		memset(map, -1, sizeof(map));
		map[sta.y][sta.x] = 0;
		while (!hoge.empty())
		{
			ma now;
			now = hoge.front();
			hoge.pop();
			for (int k = 0; k < 4; k++)
			{
				if (now.y + dy[k] >= tate || now.x + dx[k] >= yoko)continue;
				if (now.y + dy[k] < 0 || now.x + dx[k] < 0)continue;
				if (m[now.y + dy[k]][now.x + dx[k]] != 'X')
				{
					if (map[now.y + dy[k]][now.x + dx[k]] != -1)
					{
						continue;
					}
					map[now.y + dy[k]][now.x + dx[k]] = map[now.y][now.x] + 1;
					if (m[now.y + dy[k]][now.x + dx[k]] - '0' == HP)
					{
						m[now.y + dy[k]][now.x + dx[k]] = '.';
						ans += map[now.y + dy[k]][now.x + dx[k]];
						while (!hoge.empty())hoge.pop();
						HP++;
						sta.x = now.x + dx[k];
						sta.y = now.y + dy[k];
						break;
					}
					else
					{
						ma hage;
						hage.x = now.x + dx[k];
						hage.y = now.y + dy[k];
						hoge.push(hage);
					}
				}
			}

		/*	for (int i = 0; i < tate; i++)
			{
				for (int k = 0; k < yoko; k++)
				{
					cout << map[i][k] << " ";
				}
				cout << endl;
			}
			cout << endl;*/
		}
	}
	cout << ans << endl;

}

C++: #include <iostream>
#include <queue>
#include <vector>
#include <cmath>
#include <algorithm>
#include <map>

using namespace std;
using ll = long long;
const ll INF = 1e9;

int H, W, N;
vector<vector<int>> F(10);
string M[1001];

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

ll bfs(int sx, int sy, int gx, int gy) {
    ll d[1001][1001];
    queue<vector<int>> que;
    for(int i = 0; i < H; i++) for (int j = 0; j < W; j++) d[i][j] = INF;

    que.push({sx, sy});
    d[sy][sx] = 0;

    while(que.size()) {
        vector<int> p = que.front(); que.pop();
        if (p[0] == gx && p[1] == gy) break;

        for (int i = 0; i < 4; i++) {
            int nx = p[0] + dx[i], ny = p[1] + dy[i];
            if (M[ny][nx] != 'X' && nx >= 0 && nx < W && ny >= 0 && ny < H && d[ny][nx] == INF) {
                que.push({nx, ny});
                d[ny][nx] = d[p[1]][p[0]] + 1;
            }
        }
    }

    return d[gy][gx];
}

int main() {
    ll ans = 0;
    cin >> H >> W >> N;
    for (int i = 0; i < H; i++) {
        cin >> M[i];
        for (int k = 0; k < W; k++) {
            if (M[i][k] == 'S') {
                F[0] = {k, i};
            }
            if (isdigit(M[i][k])) {
                F[M[i][k] - '0'] = {k, i};
            }
        }
    }

    for (int i = 0; i < N; i++) {
        ans += bfs(F[i][0], F[i][1], F[i+1][0], F[i+1][1]);
    }

    cout << ans << endl;

    return 0;
}