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<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#include<tuple>
#define LL long long
#define TT std::tuple<int,int,int>
int ans;
int sx, sy;
int dx[] = { 0,1,-1,0 };
int dy[] = { -1,0,0,1 };
int W, H, N;
char map[1010][1010];
bool used[1010][1010];
int bfs(int &sx,int &sy,char m) {
	std::queue<TT> q;
	q.push(TT{ sx,sy,0 });
	while (true) {
		TT t = q.front();
		q.pop();
		int a, b, c;
		std::tie(a, b, c) = t;
		for (int i = 0; i < 4; i++) {
			int rx = a + dx[i];
			int ry = b + dy[i];
			if (1 <= rx&&rx <= H && 1 <= ry&&ry <= W) {
				if (map[rx][ry] == m) {
					sx = rx;
					sy = ry;
					return c + 1;
				}
				if (map[rx][ry] != 'X'&&!used[rx][ry]) {
					q.push(TT{ rx,ry,c + 1 });
					used[rx][ry] = true;
				}
			}
		}
	}
}

int main() {
	std::cin >> H >> W >> N;
	for (int i = 1; i <= H; i++) {
		for (int j = 1; j <= W; j++) {
			std::cin >> map[i][j];
			if (map[i][j] == 'S') {
				sx = i;
				sy = j;
			}
		}
	}
	char m = '0';
	for (int i = 0; i < N; i++) {
		m++;
		used[sx][sy] = true;
		ans+=bfs(sx, sy,m);
		for (int j = 1; j <= H; j++) {
			for (int k = 1; k <= W; k++) {
				used[j][k] = false;
			}
		}
	}
	std::cout << ans << std::endl;
	return 0;
}

C++: #include <cstdio>
#include <iostream>
#include <queue>
#define min(x,y) ((x)<(y)?(x):(y))
#define INFI 65535

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

int Strength = 1;
int Maps[1010][1010];
int dist[1010][1010];
int H, W, N;
int hor[] = {1,0,-1,0};
int ver[] = {0,-1,0,1};
int ans;


void clear();
void show();
P bfs(int cheese,P n);

int main(void) {
    scanf("%d %d %d\n", &H, &W, &N);
    P s,e;
    for (int i = 0; i<H; i++) {
        for (int j = 0; j<W; j++) {
            Maps[i][j] = getchar();
            if (Maps[i][j]=='S') {s.first = i; s.second = j;}
            if (Maps[i][j]=='0'+N) {e.first = i; e.second = j;}
        }
        getchar();
    }

    
    P tmp;
    tmp.first = s.first; tmp.second = s.second;
    
    for (int i = 1; i<=N; i++) {
        clear();
        tmp = bfs(i, tmp);
    }
    
    
    
    printf("%d\n", ans);
    return 0;
}

P bfs(int cheese,P n) {
    P end;
    queue<P> que;
    que.push(n);
    dist[n.first][n.second] = 0;
    
    while (que.size()) {
        P top = que.front();
        
        que.pop();
        for (int i = 0; i<4; i++) {
            int nx = top.first+ver[i], ny = top.second+hor[i];
            if (nx>=0 && nx<H && ny>=0 && ny<W && dist[nx][ny]==INFI) {
                if (Maps[nx][ny]=='.' || (isdigit(Maps[nx][ny]) && cheese!=Maps[nx][ny]-'0'))  {
                    que.push(P(nx,ny));
                    dist[nx][ny] = min(dist[nx][ny], dist[top.first][top.second]+1);
                } else if (isdigit(Maps[nx][ny]) && cheese==Maps[nx][ny]-'0') {
                    que.push(P(nx,ny));
                    dist[nx][ny] = min(dist[nx][ny], dist[top.first][top.second]+1);
                    end.first = nx; end.second = ny;
                    break;
                }
            }
        }
    }
    ans += dist[end.first][end.second];
    return end;
}

void clear() {
    for (int i = 0; i<H; i++)
        for (int j = 0; j<W; j++)
            dist[i][j] = INFI;
}

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

#define INF 1e9
#define MAX_H 1000
#define MAX_W 1000

using namespace std;

struct Cood {int x, y; };

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

char field[MAX_H][MAX_W + 1];
int d[MAX_H][MAX_W + 1];
queue<Cood> q;
int h, w, n;
int total_time = 0;

void init_bfs() {
    queue<Cood> new_q;
    swap(q, new_q);
    for (int i = 0; i < h; ++i) {
        for (int j = 0; j < w; ++j) {
            d[i][j] = INF;
        }
    }
}
/* current position (y, x) with current power 'current' & last cheeese target is 'last' */
int bfs(int sy, int sx, int target, int last) {
    init_bfs();
    int next_y, next_x;
    q.push(Cood{sx, sy});
    d[sy][sx] = 0;

    while (q.size()) {
        Cood current = q.front(); q.pop();
        if (field[current.y][current.x] == '0' + target) {
            total_time += d[current.y][current.x];
            if (target == last) {
                return total_time;
            } else {
                return bfs(current.y, current.x, target + 1, last);
            }
        }

        for (int i = 0; i < 4; ++i) {
            next_y = current.y + dy[i];
            next_x = current.x + dx[i];
            if (0 <= next_y && next_y < h && 0 <= next_x && next_x < w
                && field[next_y][next_x] != 'X' && d[next_y][next_x] == INF) {
                q.push(Cood{next_x, next_y});
                d[next_y][next_x] = d[current.y][current.x] + 1;
            }
        }
    }
}

int main() {
    //freopen("0558_1.in", "r", stdin);
    cin >> h >> w >> n;
    int sx, sy;
    for (int i = 0; i < h; ++i) {
        for (int j = 0; j < w; ++j) {
            cin >> field[i][j];
            if (field[i][j] == 'S') {
                sy = i, sx = j;
            }
        }
    }
    total_time = 0; // init
    cout << bfs(sy, sx, 1, n) << endl;
    return 0;
}