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 <vector>
#include <iostream>
#include <set>
#include <cstdio>
#include <queue>
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <ctime>
#include <cmath>
#include <complex>
#include <algorithm>
#include <tuple>
#include <algorithm>
#include <limits>
#include <map>

using namespace std;

typedef long long ll;
typedef pair<int, int> P;
typedef tuple<int, int, int> T;

P tiz[100];
char g[1100][1100];
int w, h, k;
int d[4][2] = {
    {1, 0},
    {-1, 0},
    {0, 1},
    {0, -1}
};
int used[1100][1100];
int solve(P s, P e) {
    fill_n(used[0], 1100*1100, false);
    queue<T> q;
    q.push(T(s.first, s.second, 0));
    while (!q.empty()) {
        T p = q.front(); q.pop();
        int x, y, t;
        tie(x, y, t) = p;
        if (P(x, y) == e) return t;
        if (x < 0 || w <= x || y < 0 || h <= y) continue;
        if (g[x][y] == 'X') continue;
        if (used[x][y]) continue;
        used[x][y] = true;
        for (int i = 0; i < 4; i++) {
            q.push(T(x+d[i][0], y+d[i][1], t+1));
        }
    }
    return -1;
}

int main() {
    cin >> w >> h >> k;
    for (int i = 0; i < w; i++) {
        for (int j = 0; j < h; j++) {
            char c;
            cin >> c;
            g[i][j] = c;
            if (c == 'S') {
                tiz[0] = P(i, j);
            }
            if (isdigit(c)) {
                tiz[c-'0'] = P(i, j);
            }
        }
    }
    int r = 0;
    for (int i = 0; i < k; i++) {
        r += solve(tiz[i], tiz[i+1]);
    }
    cout << r << endl;
    return 0;
}

C++: 
#include<iostream>
#include<cstdio>
#include<deque>
#include<algorithm>

using namespace std;

typedef pair<int,int>P;

const int maxn=1e3+5;
int inf=500;

int h,w,n,sx,sy;
char s[maxn][maxn];
int book[maxn][maxn],goal[10];
int Next[4][2]={{0,1},{1,0},{-1,0},{0,-1}};

int judge(int row,int col)
{
    if(row>=0&&row<h&&col>=0&&col<w){
        return 1;
    }
    return 0;
}

int bfs()
{
    int res=0;
    deque<P>q;
    for(int ci=0;ci<n;ci++){
        fill(book[0],book[0]+maxn*maxn,inf);
        q.push_back(P(sx,sy));
        book[sx][sy]=0;
        while(!q.empty()){
            int x=q.front().first;
            int y=q.front().second;
            q.pop_front();
            if((int)s[x][y]==49+ci){
                goal[ci]=book[x][y];
                sx=x;
                sy=y;
                break;
            }
            for(int i=0;i<4;i++){
                int nx=x+Next[i][0];
                int ny=y+Next[i][1];
                if(judge(nx,ny)&&s[nx][ny]!='X'&&book[nx][ny]==inf){
                    q.push_back(P(nx,ny));
                    book[nx][ny]=book[x][y]+1;
                }
            }
        }
        q.clear();
        res+=goal[ci];
    }
    return res;
}

int main()
{
    cin>>h>>w>>n;
    for(int i=0;i<h;i++){
        for(int j=0;j<w;j++){
            cin>>s[i][j];
            if(s[i][j]=='S'){
                sx=i;
                sy=j;
            }
        }
    }
    int goalnum=bfs();
    cout<<goalnum<<endl;
    return 0;
}

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

#define INF (1<<30)

typedef pair<int,int> P;

queue<P> que;
char map[1000][1000];
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(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++: //C++14 (Clang 3.8.0)

#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <string>
#define rp(i,a,b) for(int (i)=(int)(a);i<(int)(b);++i)

using namespace std;

typedef long long ll;
typedef pair<int,int> P;



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

int bfs(P x,P y,vector<vector<int>> map){
    vector<vector<bool>> d(map.size(),vector<bool>(map[0].size()));
    queue<P> que;
    que.push(x);
    d[x.first][x.second]==true;
    while(que.size()){
        P p=que.front();que.pop();
        //cout<<"lll"<<p.first<<p.second<<endl;
        if(p.first == y.first and p.second==y.second) {break;}
        for(int i=0;i<4;i++){
            int nx=p.first+dx[i];
            int ny=p.second+dy[i];
            if(0<=nx && nx<map.size() && 0<=ny &&ny<map[0].size() && map[nx][ny]!=-1 && d[nx][ny]==false){
                d[nx][ny]=true;
                que.push(P(nx,ny));
                map[nx][ny]=map[p.first][p.second]+1;
                //cout<<nx<<ny<<map[nx][ny]<<endl;
                
            }
        }
    }
    return map[y.first][y.second];

}



int main(){
    int x,y,z;
    cin>>x>>y>>z;
    vector<vector<int> > map;
    vector<pair<int,int>> pl(z+1);

    int sx,sy;
    rp(i,0,x){
        vector<int> tmp;
        string s;
        cin>>s;
        rp(j,0,y){
            if(s[j]=='X') tmp.push_back(-1);
            else if(s[j]=='.') tmp.push_back(0);
            else if(s[j]=='S') sx=i,sy=j,tmp.push_back(0);
            else {pl[(int)(s[j] - '0')]=make_pair(i,j);tmp.push_back(0);}
        }
        map.push_back(tmp);
    }

    int ans=0;
    //cout<<sx<<sy<<pl[1].first<<pl[1].second<<endl;
    ans+=bfs(P(sx,sy),pl[1],map);
    for(int i=2;i<=z;i++){
        ans+=bfs(pl[i-1],pl[i],map);
    }
    cout<<ans<<endl;
    return 0;
};