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++: //
// Create by 神舟 on 2015-02-21
//

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <cctype>
#include <stack>
#include <queue>
#include <map>
#include <string>
#include <set>
#include <vector>
using namespace std;

#define CLR(x) memset(x,0,sizeof x)
#define ll long long
#define inf 0x3f3f3f3f
const int maxn=1e3+5;
const int MOD=5e5+5;
int n,m,t,sx,sy,ex,ey;
char word[maxn][maxn];
int path[maxn][maxn];
int ans,dir[4][2]={0,1,1,0,-1,0,0,-1};

struct pnt
{
    int x,y;
    pnt(int x=0,int y=0):x(x),y(y){};
};

void bfs()
{
    memset(path,0x3f,sizeof path);
    queue <pnt> que;
    pnt p,np;
    p.x=sx,p.y=sy;
    path[sx][sy]=0;
    que.push(p);
    while(!que.empty()){
        p=que.front();que.pop();
        if(p.x==ex&&p.y==ey) {return;}
        for(int i=0;i<4;i++){
            np.x=p.x+dir[i][0];
            np.y=p.y+dir[i][1];
            if(np.x>0 && np.x<=n && np.y>0 && np.y<=m && path[np.x][np.y]>path[p.x][p.y]+1 && word[np.x][np.y]!='X')
            {
                path[np.x][np.y]=path[p.x][p.y]+1;
                que.push(np);
            }
        }
    }
}
int main()
{
#ifdef LOCAL
	freopen("in.txt","r",stdin);
	//freopen("out.txt","w",stdout);
#endif
	ios_base::sync_with_stdio(0);

	while(scanf("%d%d%d",&n,&m,&t)!=EOF){
        ans=0;
        CLR(word);
        for(int i=1;i<=n;scanf("%s",word[i++]+1));
        for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) if(word[i][j]=='S') word[i][j]='0';
        for(int k=0;k<t;k++){
            char tp=k+'0';
            for(int i=1;i<=n;i++) for(int j=1;j<=m;j++){
                if(word[i][j]==tp) sx=i,sy=j;
                if(word[i][j]==tp+1) ex=i,ey=j;
            }
            bfs();
            ans+=path[ex][ey];
            //printf("%d\t",path[ex][ey]);
        }
        printf("%d\n",ans);
	}

	return 0;
}

C++: #include <iostream>
#include <queue>

#define MAX_W 1000
#define MAX_H 1000
#define MAX_N 1000
#define INF -1

typedef std::pair<int, int> P;

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

int w, h, n;
int sx, sy, gx[MAX_N], gy[MAX_N];
char field[MAX_W][MAX_H];

int solve(int _sx, int _sy, int _gx, int _gy);

int main(){
    std::cin >> h >> w >> n;
    for(int i = 0; i < h; ++i){
        for(int j = 0; j < w; ++j){
            std::cin >> field[j][i];
            if(field[j][i] == 'S')
                sx = j, sy = i;
            
            else if(field[j][i] >= '0' && field[j][i] <= '9')
                gx[field[j][i] - '0'] = j, gy[field[j][i] - '0'] = i;
        }
    }
    
    int ans = 0;
    
    for(int i = 0; i < n; ++i){
        if(i == 0)
            ans += solve(sx, sy, gx[i + 1], gy[i + 1]);
        else
            ans += solve(gx[i], gy[i], gx[i + 1], gy[i + 1]);
    }
    
    std::cout << ans << std::endl;
    
    return 0;
}

int solve(int _sx, int _sy, int _gx, int _gy){
    int dis[MAX_W][MAX_H];
    std::queue<P> que;
    que.push(P(_sx, _sy));
    
    for(int i = 0; i < h; ++i){
        for(int j = 0; j < w; ++j)
            dis[j][i] = INF;
    }
    
    dis[_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(nx >= 0 && ny >= 0 && nx < w && ny < h && field[nx][ny] != 'X' && dis[nx][ny] == INF){
                que.push(P(nx, ny));
                dis[nx][ny] = dis[p.first][p.second] + 1;
            }
        }
    }
    
    return dis[_gx][_gy];
}

C++: #include <bits/stdc++.h>
#define PB push_back
#define MP make_pair
#define REP(i,n) for (int i=0;i<(n);i++)
#define ALL(a) (a).begin(),(a).end()
#define INF 1000000001
#define MOD 100000
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> P;
const ull B=100000007;
int dx[4]={-1,0,1,0};
int dy[4]={0,-1,0,1};
struct A{int x,y,cost;};
int main(){
      int h,w,n,fin=-1;
      int x[11],y[11];
      memset(x,-1,sizeof(x));
      memset(y,-1,sizeof(y));
      cin>>h>>w>>n;
      char c;
      bool fld[1000][1000];
      REP(i,h)REP(j,w){
            cin>>c;
            if(c=='.')fld[j][i]=true;
            else if(c=='X')fld[j][i]=false;
            else if(c=='S'){
                  fld[j][i]=true;
                  x[0]=j;y[0]=i;
            }else{
                  fld[j][i]=true;
                  x[c-'0']=j;
                  y[c-'0']=i;
                  fin=max(fin,c-'0');
            }
      }
      int ans=0;
      REP(i,fin){
            int d[1000][1000];
            memset(d,-1,sizeof(d));
            queue<A> Q;
            Q.push((A){x[i],y[i],0});
            while(!Q.empty()){
                  A a=Q.front();Q.pop();
                  int xx=a.x,yy=a.y,cost=a.cost;
//                  cout<<xx<<" "<<yy<<endl;
                  if(d[xx][yy]!=-1)continue;
                  d[xx][yy]=cost;
//                  cout<<xx<<" "<<yy<<" "<<cost<<endl;
                  if(xx==x[i+1]&&yy==y[i+1]){
                        ans+=cost;
                        break;
                  }
                  REP(j,4){
                        int nx=xx+dx[j],ny=yy+dy[j];
                        if(nx<0||nx>=w||ny<0||ny>=h||!fld[nx][ny])continue;
                        Q.push((A){nx,ny,cost+1});
                  }
            }
      }
      cout<<ans<<endl;
}