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>
using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> P;
typedef pair<ll, pair<ll, ll> > P3;

const ll MOD = ll(1e9 + 7);
const ll LLINF = LLONG_MAX;
const int IINF = INT_MAX;
const int MAX_N = int(1e5) + 5;
const double EPS = 1e-8;
int dx[] = {1, 0, -1, 0}, dy[] = {0, 1, 0, -1};
#define SORT(v) sort((v).begin(), (v).end())
#define SORTR(v) sort((v).rbegin(), (v).rend())
#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 (ll i = m; i < n; i++)

int h, w, n;
int si[10],sj[10];
int d[1005][1005];
string s[1005];

int bfs(int k) {
    REP(i,h)fill(d[i],d[i]+w,IINF);
    queue<P> que;
    d[si[k]][sj[k]] = 0;
    que.push({si[k],sj[k]});
    while(!que.empty()){
        P p = que.front();
        que.pop();
        int y = p.first, x = p.second;
        REP(m,4){
            int ny = y + dy[m], nx = x + dx[m];
            if (ny < 0 || ny >= h) continue;
            if (nx < 0 || nx >= w) continue;
            if (s[ny][nx] == 'X') continue;
            if(d[ny][nx] == IINF){
                d[ny][nx] = d[y][x] + 1;
                if(si[k+1]==ny && sj[k+1]==nx)return d[ny][nx];
                que.push({ny,nx});
            }
        }
    }
}

int main() {
    cin >> h >> w >> n;
    REP(i, h) {
        cin >> s[i];
        REP(j,w){
            if(s[i][j]=='S'){
                si[0] = i;
                sj[0] = j;
            }
            if(s[i][j]>='1' && s[i][j]<='9'){
                int x = s[i][j] - '0';
                si[x] = i;
                sj[x] = j;
            }
        }
    }
    int ans = 0;
    REP(i,n){
        ans += bfs(i);
    }
    cout << ans << endl;
    return 0;
}

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

using namespace std;

const int INF = 100000000;
const int MAX_N = 1004;
const int MAX_M = 1004;
char map[MAX_N][MAX_M];
int n, m, k, dis[MAX_N][MAX_M];
int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};

struct state {
    int x, y;
} p[12];

int bfs(int sx, int sy, int gx, int gy) {
    for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++)
            dis[i][j] = INF;
    queue<state>que;
    state start;
    start.x = sx, start.y = sy;
    dis[start.x][start.y] = 0;
    que.push(start);
    while (que.size()) {
        state cur = que.front();
        que.pop();
        if (cur.x == gx && cur.y == gy)return dis[cur.x][cur.y];
        for (int i = 0; i < 4; i++) {
            int nx = cur.x + dx[i], ny = cur.y + dy[i];
            if (dis[nx][ny] == INF && map[nx][ny] != 'X') {
                dis[nx][ny] = dis[cur.x][cur.y] + 1;
                state news;
                news.x = nx, news.y = ny;
                que.push(news);
            }
        }
    }
    return -1;
}

void solve() {

    int ans = 0;
    for (int i = 0; i <= k - 1; i++) {
        ans += bfs(p[i].x, p[i].y, p[i + 1].x, p[i + 1].y);
    }
    printf("%d\n", ans);
}

int main() {
    scanf("%d%d%d", &n, &m, &k);
    for (int i = 0; i < n; i++)
        scanf("%s", map[i]);
    for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++) {
            if (map[i][j] == 'S')
                p[0].x = i, p[0].y = j;
            if (map[i][j] != 'X' && map[i][j] != 'S') {
                int id = map[i][j] - '0';
                p[id].x = i;
                p[id].y = j;
            }
        }
    solve();
    return 0;
}

C++: #include<iostream>
#include<queue>
using namespace std;
int G[1005][1005], dist[1005][1005], H, W, K, sx[11], sy[11];
int solve(int ax, int ay, int bx, int by) {
	for (int i = 0; i < 1005 * 1005; i++)dist[i / 1005][i % 1005] = 1000000000;
	queue<pair<int, int>>Q; Q.push(make_pair(ax, ay)); dist[ax][ay] = 0;
	while (!Q.empty()) {
		int a1 = Q.front().first, a2 = Q.front().second; Q.pop();
		int dx[4] = { 1,0,-1,0 }, dy[4] = { 0,1,0,-1 };
		for (int i = 0; i < 4; i++) {
			if (G[a1 + dx[i]][a2 + dy[i]] == 0 && dist[a1 + dx[i]][a2 + dy[i]] > dist[a1][a2] + 1) {
				dist[a1 + dx[i]][a2 + dy[i]] = dist[a1][a2] + 1;
				Q.push(make_pair(a1 + dx[i], a2 + dy[i]));
			}
		}
	}
	return dist[bx][by];
}
int main() {
	cin >> H >> W >> K;
	for (int i = 0; i <= H + 1; i++) {
		for (int j = 0; j <= W + 1; j++) {
			if (i == 0 || i == H + 1 || j == 0 || j == W + 1)G[i][j] = 1;
		}
	}
	for (int i = 1; i <= H; i++) {
		for (int j = 1; j <= W; j++) {
			char p; cin >> p;
			if (p == 'S') { sx[0] = i; sy[0] = j; }
			if (p >= '0' && p <= '9') { sx[p - '0'] = i; sy[p - '0'] = j; }
			if (p == 'X')G[i][j] = 1;
		}
	}
	int cnt = 0;
	for (int i = 0; i < K; i++) {
		cnt += solve(sx[i], sy[i], sx[i + 1], sy[i + 1]);
	}
	cout << cnt << endl;
	return 0;
}

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

int H, W, N;
char field[1001][1001];
int d[1000][1000];
pair<int, int> start;
pair<int, int> cheese;
int INF = 1000000;
int result = 0;

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

void bfs()
{
    for (int n = 1; n < N + 1; n++)
    {
        queue<pair<int, int>> que;
        for (int i = 0; i < H; i++)
        {
            for (int j = 0; j < W; j++)
            {
                d[i][j] = INF;
            }
        }
        que.push(start);
        d[start.first][start.second] = 0;

        while (que.size())
        {
            pair<int, int> p = que.front();
            que.pop();
            if (field[p.first][p.second] == '0' + (char)n)
            {
                cheese = p;
                break;
            }

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

                if (0 <= nx && nx < H && 0 <= ny && ny < W && field[nx][ny] != 'X' && d[nx][ny] == INF)
                {
                    que.push(pair<int, int>(nx, ny));
                    d[nx][ny] = d[p.first][p.second] + 1;
                }
            }
        }
        result += d[cheese.first][cheese.second];
        start = cheese;
    }
}

int main() {
    scanf(" %d %d %d", &H, &W, &N);
    for (int i = 0; i < H; i++)
    {
        for (int j = 0; j < W; j++)
        {
            scanf(" %c", &field[i][j]);
            if (field[i][j] == 'S')
            {
                start.first = i;
                start.second = j;
            }
        }
    }
    bfs();
    printf("%d\n", result);
}