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++: //Name: Cheese
//Level: 2
//Category: グラフ,Graph,最短経路,幅優先探索,BFS
//Note:

/*
 * 要するに1からNまでを順番に最短経路で廻ればよい．
 * 最短経路は幅優先探索で求めることができる．
 */
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <utility>
#include <queue>

using namespace std;

const int DR[] = {0, 0, 1, -1};
const int DC[] = {1, -1, 0, 0};
struct Tag {
    int r, c, distance;
    Tag() {}
    Tag(int r, int c, int d) : r(r), c(c), distance(d) {}
};
bool visited[1000][1000];

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

    int H, W, N;
    cin >> H >> W >> N;
    vector<string> field(H);
    pair<int,int> cur;
    for(int i = 0; i < H; ++i) {
        cin >> field[i];
        size_t spos = field[i].find('S');
        if(spos != string::npos) {
            cur = make_pair(i, spos);
        }
    }
    int ans = 0;
    for(int target = 1; target <= N; ++target) {
        for(int i = 0; i < H; ++i) {
            fill_n(visited[i], W, false);
        }
        Tag route;
        queue<Tag> q;
        q.push(Tag(cur.first, cur.second, 0));
        while(!q.empty()) {
            Tag t = q.front();
            q.pop();
            for(int i = 0; i < 4; ++i) {
                int nr = t.r + DR[i];
                int nc = t.c + DC[i];
                if(0 <= nr && nr < H && 0 <= nc && nc < W) {
                    if(field[nr][nc] != 'X' && !visited[nr][nc]) {
                        visited[nr][nc] = true;
                        if(field[nr][nc] == '0'+target) {
                            route = Tag(nr, nc, t.distance+1);
                            goto found;
                        }
                        q.push(Tag(nr, nc, t.distance+1));
                    }
                }
            }
        }
found:
        ans += route.distance;
        cur = make_pair(route.r, route.c);
    }

    cout << ans << endl;
    return 0;
}

C++: // Cheese

#include <bits/stdc++.h>
using namespace std;
#pragma GCC optimize("Ofast")
#define all(x) (x).begin(),(x).end()
#define rep(i, n) for(int (i) = 0; i < (n); i++)
#define REP(i, m, n) for(int (i) = (m); (i) < (n); (i)++)
#define INF LLONG_MAX
#define MOD 1000000007
#define fcout cout << fixed << setprecision(15)
#define int long long
#define yorn(f) puts((f)?"Yes":"No")
#define YORN(f) puts((f)?"YES":"NO")
typedef long long ll;
typedef pair<int, int> P;
typedef priority_queue<int> pque;
int gcd(int a,int b){return b?gcd(b,a%b):a;};
int lcm(int a,int b){return a*b/gcd(a,b);};
int mod(int a,int b){return (a+b-1)/b;};
int month[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
template<typename A, size_t N, typename T>
void Fill(A(&array)[N],const T &val){std::fill((T*)array,(T*)(array+N),val);}
template<class T>inline bool chmax(T& a,T b){if(a < b){a=b;return true;}return false;};
template<class T>inline bool chmin(T& a,T b){if(a > b){a=b;return true;}return false;};

int h, w, n;
int Sx, Sy;
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, -1, 0, 1};
char fld[1010][1010];
int a[1010][1010];
int cx[15], cy[15];

int bfs(int sx, int sy, int gx, int gy) {
	Fill(a, INF);
	queue<P> que;
	que.push(P(sx, sy));
	a[sy][sx] = 0;

	while(que.size()) {
		P p = que.front();
		que.pop();
		rep(i, 4) {
			int nx = p.first + dx[i];
			int ny = p.second + dy[i];
			if(0 <= nx && nx < w && 0 <= ny && ny < h) {
				if(a[ny][nx] == INF && fld[ny][nx] != 'X') {
					a[ny][nx] = a[p.second][p.first] + 1;
					que.push(P(nx, ny));
				}
			}
		}
	}
	return a[gy][gx];
}

signed main() {
	cin.tie(0);
	cout.tie(0);
	ios::sync_with_stdio(false);

	cin >> h >> w >> n;
	rep(i, h) {
		string s;
		cin >> s;
		rep(j, s.size()) {
			if(s[j] == 'S') {
				Sx = j;
				Sy = i;
			} else if(isdigit(s[j])) {
				int t = s[j] - '0'; t--;
				cx[t] = j;
				cy[t] = i;
			}
			fld[i][j] = s[j];
		}
	}

	int res = bfs(Sx, Sy, cx[0], cy[0]);

	REP(i, 1, n) {
		res += bfs(cx[i - 1], cy[i - 1], cx[i], cy[i]);
	}

	cout << res << endl;
	// int A, B, C, D;
	// cin >> A >> B >> C >> D;
	// cout << bfs(A, B, C, D) << endl;

	// rep(i, n) {
	// 	cout << "Cheese " << i << " :" << cx[i] << " " << cy[i] << endl;
	// }
	return 0;
}

C++: #include <cstdio>
#include <cstring>
#include <queue>
#define P pair<int, int>
using namespace std;

const int MAX_H = 1000, MAX_W = 1000;

int H, W, N;
char C[MAX_H][MAX_W + 1];

int dx[4] = { 1,0,-1,0 }, dy[4] = { 0,1,0,-1 };
int d[MAX_H][MAX_W];
int sx, sy, gx, gy;

int bfs() {
	queue<pair<int, int>> que;
	que.push(make_pair(sx, sy));
	d[sx][sy] = 0;
	while (que.size()) {
		pair<int, int> 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 (0 <= nx && nx < H && 0 <= ny && ny < W && C[nx][ny] != 'X' && d[nx][ny] == -1) {
				que.push(make_pair(nx, ny));
				d[nx][ny] = d[p.first][p.second] + 1;
			}
		}
	}
	return d[gx][gy];
}

void solve() {
	int ans = 0;

	for (int i = 0; i < H; i++) {
		for (int j = 0; j < W; j++) {
			if (C[i][j] == 'S') {
				sx = i;
				sy = j;
			}
		}
	}

	for (int c = 1; c <= N; c++) {
		memset(d, -1, sizeof(d));

		for (int i = 0; i < H; i++) {
			for (int j = 0; j < W; j++) {
				if (C[i][j] - '0' == c) {
					gx = i;
					gy = j;
				}
			}
		}
		ans += bfs();
		sx = gx;
		sy = gy;
	}

	printf("%d\n", ans);
}

int main() {
	scanf("%d %d %d", &H, &W, &N);
	for (int i = 0; i < H; i++) {
		scanf("%s", C[i]);
	}

	solve();
}