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 <bits/stdc++.h>
#define rep(i,a,b) for(int i=a;i<(b);++i)
#define erep(i,a,b) for(int i=a;i<=(int)(b);++i)
#define per(i,a,b) for(int i=(a);i>(b);--i)
#define eper(i,a,b) for(int i=(a);i>=b;--i)
#define fore(i, x, a) for(auto &&x:a) 
#define ITR(i,b,e) for(auto i=(b);i!=(e);++i)
#define pb push_back
#define mp make_pair
#define MOD 1000000007
#define ALL(x) begin(x),end(x)
#define F first
#define S second
const int inf=1001001001; const long long INF=1001001001001001001;
using namespace std;
using ll = long long;
using pii = pair<int,int>;
using vii = vector<int>;
using vll = vector<ll>;
using priority_queue_small = priority_queue<tuple<int, int, int>, vector<tuple<int, int, int>>, greater<tuple<int, int, int>> >;
template<class T>using vv = vector<T>;
template<class T>bool chmax(T &a, const T &b) { if (a<b) { a = b; return 1; } return 0; }
template<class T>bool chmin(T &a, const T &b) { if (b<a) { a = b; return 1; } return 0; }
template<class T> ostream& operator<<(ostream &os,const vector<T> &v) {
    ITR(i,begin(v),end(v))os<<*i<<(i==end(v)-1?"":" ");return os;}
template<class T> istream& operator>>(istream &is,vector<T> &v) {
    ITR(i,begin(v),end(v)) is>>*i;return is;}
template<class T,class U> istream& operator>>(istream &is, pair<T,U> &p) {
    is>>p.first>>p.second;return is;}
template<class T>T gcd(T a, T b){ return b ? gcd(b, a % b) : a; }
template<class T>T lcm(T a, T b){ return a / gcd(a, b) * b; }
int dx[]={0,1,0,-1},dy[]={1,0,-1,0};
int h, w, n, d[1001][1001];
char g[1001][1001];

int bfs(pii from , pii to) { 
  queue<pii> q;
  q.push(from);
  d[from.F][from.S] = 0;
  while (!q.empty()) {
    pii p = q.front(); q.pop();
    if (p == to) break;
    rep(i, 0, 4) {
      int nx = p.F + dx[i], ny = p.S + dy[i];
      if (0 <= nx && nx <h && 0 <= ny && ny < w && d[nx][ny] == -1 && g[nx][ny] != 'X') {
        d[nx][ny] = d[p.F][p.S] + 1;
        q.push({nx, ny});
      } 
    }
  }
  return d[to.F][to.S];
}

int main() {
 cin.tie(0);
 ios::sync_with_stdio(false);
  cin >> h >> w >> n;
  pii v[10];
  string tmp = "S123456789";
  for(int i=0;i<h;i++){
    for(int j=0;j<w;j++){
      cin >> g[i][j];
      for(int k=0;k<=n;k++){
        if(g[i][j] == tmp[k]) v[k] = {i,j};
      }
    }
  }
  int cnt = 0;
  for(int i=1;i<=n;i++){
    memset(d,-1,sizeof(d));
    cnt += bfs(v[i-1],v[i]);
  }
  cout << cnt << endl;
  return 0;
}

C++: #include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <map>
#include <sstream>
#include <functional>
#include <numeric>
#include <cmath>
#include <cstring>
#include <cstdio>
#include <queue>
#include <stack>
#include <set>

using namespace std;

#define ALL(co) co.begin(), co.end()
#define tpl(...) make_tuple(__VA_ARGS__)

typedef long long LL;
typedef pair<int, int> P; typedef pair<P, int> PI; typedef pair<P, P> PP;
typedef vector<int> Array; typedef vector<vector<int> > Array2;
typedef vector<LL> LArray; typedef vector<P> PArray; typedef vector<string> SArray;

const int INF = 1 << 29;
const LL LINF = 1LL << 60;

inline int getInt() { int itiv; return (cin >> itiv, itiv); }
template <typename T> void readAll(vector<T>& vec) { for (int i = 0, size = vec.size(); i < size; i++) cin >> vec[i]; }
template <typename T, typename U> void readAll(vector<pair<T, U> >& vec) { for (int i = 0, size = vec.size(); i < size; i++) cin >> vec[i].first >> vec[i].second; }
template < typename T > inline string toString( const T &a ){ ostringstream oss; oss << a; return oss.str(); };
inline bool between(int min, int max, int n) { return min <= n && n <= max; }
inline bool inRange(int begin, int end, int n) { return begin <= n && n < end; }
inline bool inRange(int size, int n) { return 0 <= n && n < size; }

int dx[] = { -1, 0, 1, 0 }, dy[] = { 0, -1, 0, 1 };
int dr[] = { 0, -1, 0, 1 }, dc[] = { -1, 0, 1, 0 };
bool visited[1000][1000];
char stage[1000][1000];
int h, w, n;

int main(void)
{
	ios::sync_with_stdio(false);
	while(cin >> h >> w >> n && n)
	{
		PArray goals(n + 1);
		for (int i = 0; i < h; i++)
		{
			for (int j = 0; j < w; j++)
			{
				cin >> stage[i][j];
				if(stage[i][j] == 'S') goals[0] = P(i, j);
				int num = stage[i][j] - '0';
				if(inRange(n + 1, num)) goals[num] = P(i, j);
			}
		}

		int ans = 0;
		queue<PI> que;
		for (int i = 0; i < n; i++)
		{
			P start = goals[i], goal = goals[i + 1];
			memset(visited, false, sizeof(visited));
			que = queue<PI>();
			que.push(PI(start, 0));
			while (!que.empty())
			{
				PI pi = que.front(); que.pop();
				if(goal == pi.first)
				{
					ans += pi.second;
					break;
				}
				int r = pi.first.first, c = pi.first.second;
				visited[r][c] = true;

				for (int i = 0; i < 4; i++)
				{
					int nr = r + dr[i], nc = c + dc[i];
					if(!inRange(h, nr) || !inRange(w, nc) || stage[nr][nc] == 'X' || visited[nr][nc]) continue;
					que.push(PI(P(nr, nc), pi.second + 1));
				}
			}
		}
		cout << ans << endl;
	}
	return 0;
}

C++: #include<iostream>
#include<cstring>
#include<queue>
#include<cstdio>
#include<algorithm>

int h,w,n,nxtx,nxty,startx,starty,ans,dir[4][2]={{0,1},{0,-1},{-1,0},{1,0}};
char map[1005][1005];
bool flag[1005][1005];
using namespace std;

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

int bfs(point a,point b)
{
	memset(flag,false,sizeof(flag));
	queue<point> que;
	a.step=0;flag[a.x][a.y]=true;
	que.push(a);
	while(!que.empty())
	{
		for(int i=0;i<4;i++)
		{
			temp=que.front();
			nxtx=temp.x+dir[i][0];nxty=temp.y+dir[i][1];
			if(nxtx<0||nxty<0||nxtx>=h||nxty>=w||flag[nxtx][nxty]||map[nxtx][nxty]=='X') continue;
			flag[nxtx][nxty]=true;
			temp.step++;temp.x+=dir[i][0];temp.y+=dir[i][1];
			que.push(temp);
			if(nxtx==b.x&&nxty==b.y)
			   return temp.step;
		}
		que.pop();
	}
	return -1;
}

int main()
{
	ans=0;
	scanf("%d%d%d",&h,&w,&n);
	for(int i=0;i<h;i++)
	{
		getchar();
		for(int j=0;j<w;j++)
		{
			scanf("%c",&map[i][j]);
			if(map[i][j]=='S'){des[0].x=i;des[0].y=j;}
			if(map[i][j]<='9'&&map[i][j]>='1')
			{des[map[i][j]-'0'].x=i;des[map[i][j]-'0'].y=j;}
		}
	}
	for(int i=0;i<n;i++)
	   ans+=bfs(des[i],des[i+1]);
	printf("%d\n",ans);
}