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<queue>
#include<cstring>
#include<cstdio>
#include<algorithm>
char map[1100][1100];
bool flag[1100][1100];
int m,n,k,ans=0,dir[4][2]={{-1,0},{0,-1},{0,1},{1,0}};
using namespace std;

struct point{
	int x,y,step;
}temp,flg[15];

int bfs(point a,point b)
{
	queue<point> que;
	temp=a;temp.step=0;
	que.push(temp); 
	flag[temp.x][temp.y]=true;
	while(!que.empty()){
		for(int i=0;i<4;i++){
			temp=que.front();
			int nxtx=temp.x+dir[i][0],nxty=temp.y+dir[i][1];
			if(nxtx<0||nxty<0||nxtx>=m||nxty>=n) continue;
	        if(flag[nxtx][nxty]||map[nxtx][nxty]=='X') continue;
			flag[nxtx][nxty]=true;
			temp.x+=dir[i][0],temp.y+=dir[i][1];temp.step++;	
			que.push(temp);
			if(nxtx==b.x&&nxty==b.y)
			   return temp.step;	
		}
		que.pop();
	}
	return -1;
}
int main()
{
	scanf("%d%d%d",&m,&n,&k);
	for(int i=0;i<m;i++){
		getchar();
		for(int j=0;j<n;j++){
			scanf("%c",&map[i][j]);
			if(map[i][j]=='S') flg[0].x=i,flg[0].y=j;
			else if(map[i][j]<='9'&&map[i][j]>='1') flg[map[i][j]-'0'].x=i,flg[map[i][j]-'0'].y=j;
		}
	}
	for(int i=0;i<k;i++){
	    memset(flag,false,sizeof(flag));
	    ans+=bfs(flg[i],flg[i+1]);
	}
	cout << ans << endl;
 }

C++: # include <iostream>
# include <algorithm>
#include <array>
# include <cassert>
#include <cctype>
#include <climits>
#include <numeric>
# include <vector>
# include <string>
# include <set>
# include <map>
# include <cmath>
# include <iomanip>
# include <functional>
# include <tuple>
# include <utility>
# include <stack>
# include <queue>
# include <list>
# include <bitset>
# include <complex>
# include <chrono>
# include <random>
# include <limits.h>
# include <unordered_map>
# include <unordered_set>
# include <deque>
# include <cstdio>
# include <cstring>
#include <stdio.h>
#include <stdlib.h>
#include <cstdint>
#include <cfenv>
//#include <bits/stdc++.h>
using namespace std;
using LL = long long;
using ULL = unsigned long long;
constexpr long long MOD = 1000000000 + 7;
constexpr long long INF = std::numeric_limits<long long>::max();
const double PI = acos(-1);
#define fir first
#define sec second
#define thi third
#define debug(x) cerr<<#x<<": "<<x<<'\n'
typedef pair<LL, LL> Pll;
typedef pair<LL, pair<LL, LL>> Ppll;
typedef pair<LL, pair<LL, bitset<100001>>> Pbll;
typedef pair<LL, pair<LL, vector<LL>>> Pvll;
typedef pair<LL, LL> Vec2;
struct Tll { LL first, second, third; };
typedef pair<LL, Tll> Ptll;
#define rep(i,rept) for(LL i=0;i<rept;i++)
#define Mfor(i,mf) for(LL i=mf-1;i>=0;i--)
LL h, w, n, m, k, s, t, q, sum, last, cnt, ans;
Pll a[110];
LL d[1010][1010];
int dd[4][2] = { {1,0},{0,1},{ -1,0 },{ 0,-1 } };
string str,ss;
struct Edge { LL cost, from, to; };
vector<Edge>vec;
bool f;
char c[10000][10000];
void YN(bool f) {
	if (f)
		cout << "YES" << endl;
	else
		cout << "NO" << endl;
}
void yn(bool f) {
	if (f)
		cout << "Yes" << endl;
	else
		cout << "No" << endl;
}
LL bfs(Pll s,Pll t) {
	queue<Ppll>qu;
	d[s.fir][s.sec] = 0;
	qu.push(Ppll(d[s.first][s.second], s));
	while (!qu.empty()) {
		Ppll pp = qu.front();
		Pll pos = pp.second;
		qu.pop();
		if (pos == t)break;
		if (pp.fir > d[pos.fir][pos.sec])continue;
		rep(i, 4) {
			LL X = pos.first + dd[i][0], Y = pos.second + dd[i][1];
			if (X < h&&Y<w&&X>=0&&Y>=0&&d[X][Y]>d[pos.fir][pos.sec] + 1&&c[X][Y]== '.') {
				d[X][Y] = d[pos.first][pos.second] + 1;
				qu.push(Ppll(d[X][Y], Pll(X, Y)));
			}
		}
	}
	return d[t.fir][t.sec];
}
int main() {
	cin >> h >> w >> n;
	rep(i, h)rep(j, w) {
		cin >> c[i][j];
		if (c[i][j] == 'S' || (c[i][j] > '0'&&c[i][j] <= '9')) {
			if (c[i][j] == 'S')
				a[0] = Pll(i, j);
			if (c[i][j] > '0'&&c[i][j] <= '9')
				a[c[i][j] - '0'] = Pll(i, j);
			c[i][j] = '.';
		}
	}
	rep(i, n) {
		rep(j, 1010)rep(k, 1010)d[j][k] = 30000;
		ans += bfs(a[i],a[i+1]);
	}
	cout << ans << endl;
	return 0;
}

C++: #include <iostream>
#include <string>
#include <algorithm>
#include <cstdio>
#include <vector>
#include <queue>

using namespace std;
typedef long long ll;
typedef pair<int,int> P;

const int INF = 9999999;

vector <string> map;
int Sx,Sy;

int dx[4]={1,0,-1,0},dy[4]={0,1,0,-1};
int H,W,N;
int bfs(int target,vector<vector<int> > d){
  queue<P> que;
  que.push(P(Sx,Sy));
  d[Sy][Sx]=0;
  P p;
  while(que.size()){
	p = que.front(); que.pop();
	if((int)(map[p.second][p.first]-'0') == target)break;
	for(int i=0;i<4;++i){
  	int nx = p.first+dx[i];
  	int ny = p.second+dy[i];
  	if(0<=nx&&0<=ny && nx<W&&ny<H && map[ny][nx]!='X' && d[ny][nx] == INF ){
      que.push(P(nx,ny));
      d[ny][nx]=d[p.second][p.first]+1;
  	}
	}
  }
  Sx=p.first; Sy=p.second;
  return d[p.second][p.first];
}

int main(){
  int ans = 0;
  cin >> H >> W >> N;
  for(int i=0;i<H;++i){
	string temp;
	cin >> temp;
	for(int j=0;j<W;++j)
  	if(temp[j]=='S'){
      Sx=j;
      Sy=i;
  	 }
	   map.push_back(temp);
  }
  vector<vector<int> > d;
  vector<int> x;x.resize(W,INF);
  for(int i=0;i<H;++i)d.push_back(x);
  for(int i=1;i<=N;++i)ans+=bfs(i,d);
  cout << ans << endl;
}

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

const int INF = 2000000;
char fl[1010][1010];
int d[1010][1010];

int bfs(int sx, int sy, int gx, int gy, int mx, int my) {
	typedef pair<int, int>P;
	int dx[4] = { 1,0,-1,0 }, dy[4] = { 0,1,0,-1 };

	for (int i = 0;i < mx;i++)
		for (int j = 0;j < my;j++)d[i][j] = INF;

	queue<P>que;
	que.push(P(sx, sy));
	d[sx][sy] = 0;

	while (que.size()) {
		P p = que.front();
		que.pop();

		if (p.first == gx&&p.second == gy)break;

		for (int i = 0;i < 4;i++) {
			int nx = p.first + dx[i], ny = p.second + dy[i];

			if (0 <= nx&&nx < mx && 0 <= ny&&ny < my&&fl[nx][ny] != 'X'&&d[nx][ny] == INF) {
				que.push(P(nx, ny));
				d[nx][ny] = d[p.first][p.second] + 1;
			}
		}
	}
	return d[gx][gy];
}

int main() {
	int h, w, n;
	cin >> h >> w >> n;
	int al = 0;
	for (int i = 0;i < h;i++) {
		for (int j = 0;j < w;j++) { cin >> fl[i][j]; 
		}
	}
	char a[10] = { 'S','1','2','3','4','5','6','7','8','9' };
	for (int i = 0;i < n;i++) {
		int sx, sy;
		int gx, gy;
		for (int j = 0;j < h;j++) {
			for (int k = 0;k < w;k++) {

				if (fl[j][k]== a[i]) {
					sx = j;
					sy = k;
				}
				if (fl[j][k]== a[i+1]) {
					gx = j;
					gy = k;
				}
			}
		}

		al += bfs(sx, sy, gx, gy,h,w);
	}
	
	cout << al << endl;
	getchar();
	getchar();
	return 0;
}