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 <cstring>
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
int w, h, n;
char map[1024][1024];
int d[1024][1024];
const int direction[4][2] = {
    { -1, 0 },
    { 1, 0 },
    { 0, -1 },
    { 0, 1 },
};
int factory[16][2];
typedef pair<int, int> P;
/*int bfs(int sx, int sy, int gx, int gy) {
    for (int i = 0; i < h; ++i) {
        for (int j = 0; j < w; ++j) {
            d[i][j] = -1;
        }
    }
    queue<P> que;
    que.push(P(sx, sy));
    d[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 + direction[i][0];
            int ny = p.second + direction[i][1];
            if (0 <= nx && nx < h && 0 <= ny && ny < w && map[nx][ny] != 'X' && d[nx][ny] == -1) {
                que.push(P(nx, ny));
                d[nx][ny] = d[p.first][p.second] + 1;
            }
        }
    }

    return d[gx][gy];
}*/
int bfs(int sx, int sy, int ex, int ey){
    for(int i = 0; i < h; i++){
        for(int j = 0; j < w; j++)
            d[i][j] = -1;
    }
    queue <P> q;
    q.push(P(sx, sy));
    d[sx][sy] = 0;
    while(!q.empty()){
        P p = q.front();
        q.pop();
        if(p.first == ex && p.second == ey)
            break;
        for(int i = 0; i < 4; i++){
            int dx = p.first + direction[i][0];
            int dy = p.second + direction[i][1];
            if(dx >= 0 && dy >= 0 && dx < h && dy < w && map[dx][dy] != 'X' && d[dx][dy] == -1)
                q.push(P(dx, dy));
                d[dx][dy] = d[p.first][p.second] + 1;
        }
    }
    return d[ex][ey];
}
/*int main() {

    cin >> h >> w >> n;
    for (int i = 0; i < h; ++i) {
        for (int j = 0; j < w; ++j) {
            cin >> map[i][j];
        }
    }

    for (int i = 0; i < h; ++i) {
        for (int j = 0; j < w; ++j) {
            if (map[i][j] == 'S') {
                factory[0][0] = i;
                factory[0][1] = j;
                map[i][j] = '.';
            } else if (isdigit(map[i][j])) {
                int index = map[i][j] - '0';
                factory[index][0] = i;
                factory[index][1] = j;
            }
        }
    }

    int step = 0;
    for (int i = 0; i < n; ++i) {
        step += bfs(factory[i][0], factory[i][1], factory[i + 1][0], factory[i + 1][1]);
    }

    cout << step << endl;

    return 0;
}*/
int main() {
    scanf("%d %d %d", &h, &w, &n);
    for(int i = 0; i < h; i++)
        scanf("%s", map[i]);
    for(int i = 0; i < h; i++) {
        for(int j = 0; j < w; j++) {
            if(map[i][j] == 'S') {
                factory[0][0] = i;
                factory[0][1] = j;
                map[i][j] = '.';
            } else if(isdigit(map[i][j])) {
                factory[map[i][j] - '0'][0] = i;
                factory[map[i][j] - '0'][1] = j;
                map[i][j] = '.';
            }
        }
    }
    int ans = 0;
    for(int i = 0; i < n; i++)
        ans += bfs(factory[i][0], factory[i][1], factory[i + 1][0], factory[i + 1][1]);
    printf("%d\n", ans);
    return 0;
}
///////////////////////////End Sub//////////////////////////////////

C++: #include <bits/stdc++.h>

using namespace std;
typedef long long ll;
typedef pair<int,int> P;

int h,w;
int n;
char field[1001][1001];
int sx,sy;
int dx[4] = {1,0,-1,0};
int dy[4] = {0,1,0,-1};

int bfs(char tn){
	queue<P> que; que.push(P(sx,sy));
	int d[1001][1001];
	for (int i = 0;i < h;i++){
		for (int j = 0;j < w;j++){
			d[i][j] = INT_MAX;
		}
	}
	d[sy][sx] = 0;
	while(!que.empty()){
		P p = que.front(); que.pop(); 
		int x = p.first, y = p.second;
		//cout << x << " " << y << endl;
		if(field[y][x] == tn){
			sx = x; sy = y;
			return d[y][x];
		}
		for (int i = 0;i < 4;i++){
			int nx = x+dx[i], ny = y+dy[i];
			//cout << nx << " " << ny << endl;
			if(nx >= 0 && ny >= 0 && nx < w && ny < h && d[ny][nx] == INT_MAX && field[ny][nx] != 'X'){
				d[ny][nx] = d[y][x]+1;
				que.push(P(nx,ny));
			}
		}
	}
	return -1;
}

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

	cin >> h >> w >> n;

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

	int ans = 0;

	for (int i = 1;i <= n;i++){
		ans += bfs('0'+i);
	}

	cout << ans << endl;

	return 0;

}

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

using namespace std;
const int INF = -1;
const int MaxH = 1000;
const int MaxW = 1000;
const int MaxN = 10;
int h,w;
char ma[MaxH][MaxW];
int dx[4] = {1,0,-1,0};
int dy[4] = {0, 1, 0, -1};
int N;
int res;
int cx[10], cy[10];
int t[MaxH][MaxW];
typedef pair<int,int> P;

int dfs(int start){
    queue<P> que;
    for(int i = 0; i < h; i++){
        for(int j = 0; j < w; j++){
            t[i][j] = INF;
        }
    }
    int sx = cx[start];
    int sy = cy[start];
    int ex = cx[start+1];
    int ey = cy[start+1];
    que.push(P(sy,sx));
    t[sy][sx] = 0;
    while(que.size()){
        P p = que.front();
        que.pop();
        if(p.first == ey && p.second == ex) break;
        for(int i = 0; i< 4; i++){
            int ny = p.first + dy[i];
            int nx = p.second + dx[i];
            if (0 <= nx && nx < w && 0 <= ny && ny < h && ma[ny][nx] != 'X' && t[ny][nx] == INF){
                t[ny][nx] = t[p.first][p.second] + 1;
                que.push(P(ny,nx));
            }
        }
    }
    return t[ey][ex];
}

void solve(){
    res = 0;
    cin >> h >> w >> N;
    for(int i = 0; i < h; i++){
        for(int j = 0; j < w; j++){
            cin >> ma[i][j];
            if(ma[i][j] == 'S'){
                cx[0] = j;
                cy[0] = i;
            }
            if(ma[i][j] >= '1' && ma[i][j] <= '9' ){
                cx[ma[i][j] - '0'] = j;
                cy[ma[i][j] - '0'] = i;
            }
        }
    }
    for (int i = 0; i < N;i++){
        res += dfs(i);
    }
    cout << res << endl;
}

int main() {
    ios_base::sync_with_stdio(false);
    solve();
    return 0;
}