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<cmath>
#include<cassert>
#include<iostream>
#include<sstream>
#include<string>
#include<vector>
#include<queue>
#include<set>
#include<map>
#include<utility>
#include<numeric>
#include<algorithm>
#include<bitset>
#include<complex>

using namespace std;

typedef long long Int;
typedef vector<int> vint;
typedef pair<int,int> pint;
#define mp make_pair

template<class T> void pv(T a, T b) { for (T i = a; i != b; ++i) cout << *i << " "; cout << endl; }
template<class T> void chmin(T &t, T f) { if (t > f) t = f; }
template<class T> void chmax(T &t, T f) { if (t < f) t = f; }
int in() { int x; scanf("%d", &x); return x; }

class hoge{
public:
	hoge(int x,int y,int cost){this->x=x;this->y=y;this->cost=cost;}
	int x,y,cost;
	bool operator<(const hoge h)const{return this->cost<h.cost;}
	bool operator>(const hoge h)const{return this->cost>h.cost;}
};

string str[1010];
int di[1010][1010];
priority_queue<hoge,vector<hoge>,greater<hoge> > d;
int h,w,n;

int dis(int ax,int ay,int bx,int by){
	while(!d.empty())d.pop();
	memset(di,-1,sizeof(di));
	hoge tmp(ax,ay,0);
	d.push(tmp);
	while(!d.empty()){
		hoge top=d.top();
		int x=top.x;
		int y=top.y;
//cout<<x<<" "<<y<<" "<<top.cost<<endl;
		d.pop();
		if(x<0||w<=x||y<0||h<=y)continue;
		if(di[y][x]!=-1&&di[y][x]<=top.cost)continue;
		if(str[y][x]=='X')continue;
		di[y][x]=top.cost;
		top.cost++;
		top.x++;
		d.push(top);
		top.x--;
		top.x--;
		d.push(top);
		top.x++;
		top.y++;
		d.push(top);
		top.y--;
		top.y--;
		d.push(top);
	}
	return di[by][bx];
}

int main() {
	cin>>h>>w>>n;
	int i,j,k;
	for(i=0;i<h;i++){
		cin>>str[i];
	}
	int ax,ay,bx,by,res=0;
	for(i=1;i<=n;i++){
		if(i==1){
			for(j=0;j<h;j++){
				for(k=0;k<w;k++){
					if(str[j][k]=='S'){
						ax=k;
						ay=j;
					}
					if(str[j][k]=='0'+i){
						bx=k;
						by=j;
					}
				}
			}
			res+=dis(ax,ay,bx,by);
		}else{
			for(j=0;j<h;j++){
				for(k=0;k<w;k++){
					if(str[j][k]=='0'+i-1){
						ax=k;
						ay=j;
					}
					if(str[j][k]=='0'+i){
						bx=k;
						by=j;
					}
				}
			}
			res+=dis(ax,ay,bx,by);
		}
	}
	cout<<res<<endl;
	return 0;
}

C++: #include<iostream>
#include<vector>
#include<algorithm>
#include<cctype>
#include<utility>
#include<string>
#include<cmath>
#include<cstring>
#include<queue>
#include<map>
#include<climits>

#define REP(i, n) for(int i = 0;i < n;i++)
#define REPR(i, n) for(int i = n;i >= 0;i--)
#define FOR(i, m, n) for(int i = m;i < n;i++)
#define FORR(i, m, n) for(int i = m;i >= n;i--)
#define SORT(v, n) sort(v, v+n);
#define VSORT(v) sort(v.begin(), v.end());
#define llong long long
#define pb(a) push_back(a)
using namespace std;
typedef pair<int, int> pii;
typedef long long int ll;
typedef pair<ll,ll> LLP;
int dx[4] = {1,0,0,-1};
int dy[4] = {0,1,-1,0};
//#define INF 1000000007
#define ARRAY_MAX 1005
const int INF = 1e9+7;

int h,w,n;
char mp[ARRAY_MAX][ARRAY_MAX];
int mini[ARRAY_MAX][ARRAY_MAX];
int sx,sy;

int bfs(int y,int x,int goal){
    //y座標、x座標、食べられるチーズを作る工場

    for(int i = 0;i < ARRAY_MAX;i++){
        for(int j = 0;j < ARRAY_MAX;j++){
            mini[i][j] = -1;
        }
    }
    queue<pii> que;
    que.push(pii(y,x));
    mini[sy][sx] = 0;

    while(!que.empty()){

        pii now = que.front();
        que.pop();
        int now_y = now.first;
        int now_x = now.second;
        if(mp[now_y][now_x] == '0'+goal){
            sy = now_y;
            sx = now_x;//次の始点が今の終点になる。
            return mini[now_y][now_x];
        }

        for(int i = 0;i < 4;i++){
            int ny = now_y + dy[i];
            int nx = now_x + dx[i];
            if(0 <= ny && ny < h && 0 <= nx && nx < w && mp[ny][nx] != 'X' && mini[ny][nx] == -1){
                mini[ny][nx] = mini[now_y][now_x] + 1;
                que.push(pii(ny,nx));
            }
        }
    }
}

int main(){

    cin >> h >> w >> n;
    for(int i = 0;i < h;i++){
        scanf("%s",mp[i]);
    }

    for(int i = 0;i < h;i++){
        for(int j = 0;j < w;j++){
            if(mp[i][j] == 'S'){
                sy = i;
                sx = j;
                break;
            }
        }
    }

    int ans = 0;

    for(int i = 1;i <= n;i++){
        ans += bfs(sy,sx,i);
    }
    cout << ans << endl;

    return 0;
}

C++: #include<bits/stdc++.h>
using namespace std;

typedef long long ll;

const int MAX_N = 1010;
char grid[MAX_N][MAX_N];
bool visited[MAX_N][MAX_N];
int goals[11][2];
int h, w, n;

typedef pair<int,int> P;

int dir[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};
int bfs(int sx, int sy, int ex, int ey) {
    queue<P> que;
    visited[sx][sy] = true;
    que.push(P(sx, sy));
    int step = 0;
    while(!que.empty()) {
        for(int size = que.size(); size ; size--) {
            P cur = que.front(); que.pop();
            int x = cur.first, y = cur.second;
            if(x == ex && y == ey) return step;
            for(int i = 0; i < 4; i++) {
                int nx = x + dir[i][0], ny = y + dir[i][1];
                if(nx >= 0 && nx < h && ny >= 0 && ny < w && grid[nx][ny] != 'X' && !visited[nx][ny]) {
                    visited[nx][ny] = true;
                    que.push(P(nx, ny));
                }
            }
        }
        step++;
    }
    return 0;
}

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cin >> h >> w >> n;
    for(int i = 0; i < h; i++) {
        for(int j = 0; j < w; j++) {
            cin >> grid[i][j];
            if(grid[i][j] == 'S') {
                goals[0][0] = i;
                goals[0][1] = j;
            }
            if(grid[i][j] >= '1' && grid[i][j] <= '9') {
               goals[grid[i][j] - '0'][0] = i;
               goals[grid[i][j] - '0'][1] = j;
            }
        }
    }
    int ans = 0;
    for(int i = 1; i <= n; i++) {
        memset(visited, false, sizeof(visited));
        ans += bfs(goals[i-1][0], goals[i-1][1], goals[i][0], goals[i][1]);
    }
    cout << ans << "\n";
    return 0;
}