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 <cstdio>
#include <utility>
#include <queue>
using namespace std;

typedef pair<int, int> Pair;
const int INF = 100000000;

int H, W, N;
const int MAX_H = 1000, MAX_W = 1000;
char plant[MAX_H][MAX_W];
int sx, sy;
int dx[4] = {0,1,0,-1}, dy[4] = {1,0,-1,0};
int d[MAX_H][MAX_W];
int mytime;

void bfs() {
    queue<Pair> que;
    for (int i = 0; i < H; i++) {
        for (int j = 0; j < W; j++) {
            d[i][j] = INF;
        }
    }
    char muscle = '1';
    que.push(Pair(sx,sy));
    d[sx][sy] = 0;
    while (que.size()) {
        Pair p  = que.front(); que.pop();
        if (int(muscle)-49 == N) 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 && plant[nx][ny] != 'X' && d[nx][ny] == INF) {
                que.push(Pair(nx, ny));
                d[nx][ny] = d[p.first][p.second] + 1;
            }
            if (muscle == plant[nx][ny]) {
                while(que.size()) {que.pop();}
                que.push(Pair(nx, ny));
                muscle = muscle + 1;
                mytime += d[nx][ny];
                for (int i = 0; i < H; i++) {
                    for (int j = 0; j < W; j++) {
                        d[i][j] = INF;
                    }
                }
                d[nx][ny] = 0;
                break;
            }
        }
    }
}

// void solve() {
//     time = 0;
//     bfs();
//     cout << time << endl;
// }

// int main () {
//     cin >> H >> W >> N;
//     for (int i = 0; i < H; i++) {
//         for (int j = 0; j < W; j++) {
//             cin >> plant[i][j];
//             if(plant[i][j] == 'S') {sx = i; sy = j;}
//         }
//     }
//     solve();
// }

void solve() {
    mytime = 0;
    bfs();
    printf("%d",mytime);
}

int main () {
    scanf("%d%d%d",&H,&W,&N);
    for (int i = 0; i < H; i++) {
        scanf("%s", plant[i]);
        for (int j = 0; j < W; j++) {
            if(plant[i][j] == 'S') {sx = i; sy = j;}
        }
    }
    solve();
}

C++: #include <iostream>
#include <iomanip>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <algorithm>
#include <cstdio>
#include <utility>
#include <string>
#include <cmath>
#include <cstdlib>
#include <cstring>

using namespace std;

typedef uint64_t u64;
typedef int64_t s64;
typedef uint32_t u32;
typedef int32_t s32;
typedef vector<s32> vs32;
typedef vector<u32> vu32;
typedef vector<s64> vs64;
typedef vector<u64> vu64;

const double PI=3.14159265358979323846;

#define MAX(x, y) ((x) < (y) ? (y) : (x))
#define MIN(x, y) ((x) > (y) ? (y) : (x))

#define rep(i, N) for(int i = 0; i < N; ++i)

#define CEIL(x, y) (((x) + (y) - 1) / (y))
#define MOD 1000000007ULL

#define IN(l, r, x) ((l) <= (x) && (x) < (r))

struct Point
{
    int x, y;
};

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

    int h, w, n;
    cin >> h >> w >> n;
    vector< string > field(h);
    rep (i, h) cin >> field[i];

    vector< Point > vp(n);
    Point s;
    rep (i, h)
    {
        rep (j, w)
        {
            if (field[i][j] == 'S')
            {
                s.y = i; s.x = j;
            }
            else if (field[i][j] != 'X' && field[i][j] != '.')
            {
                vp[field[i][j] - '1'] = Point{.x = j, .y = i};
            }
        }
    }

    int dy[] = {-1, 0, 1, 0};
    int dx[] = {0, -1, 0, 1};
    int ans = 0;
    rep (i, n)
    {
        queue< Point > q;
        q.push(s);
        vector< vs32 > d(h, vs32(w, (int)1e9));
        d[s.y][s.x] = 0;
        while (!q.empty())
        {
            Point p = q.front(); q.pop();
            rep (j, 4)
            {
                int ny = p.y + dy[j];
                int nx = p.x + dx[j];
                if (IN(0, h, ny) && IN(0, w, nx) && field[ny][nx] != 'X' && d[ny][nx] > d[p.y][p.x] + 1)
                {
                    q.push(Point{.x = nx, .y = ny});
                    d[ny][nx] = d[p.y][p.x] + 1;
                }
            }
        }
        ans += d[vp[i].y][vp[i].x];
        s.y = vp[i].y; s.x = vp[i].x;
    }

    cout << ans << "\n";
    return 0;
}

C++: #include <algorithm>
#include <cstring>
#include <iostream>
#include <queue>
using namespace std;

int dx[] = {1, 0, -1, 0}, dy[] = {0, 1, 0, -1};
char field[1000][1000];

class Data {
   public:
    int x, y, count;
    Data() {}
    Data(int x, int y, int count) : x(x), y(y), count(count) {}
};
int main() {
    int h, w, n;
    cin >> h >> w >> n;
    Data start;
    int ans = 0;
    for (int i = 0; i < h; i++) {
        cin >> field[i];
        for (int j = 0; j < w; j++) {
            if (field[i][j] == 'S') {
                start = Data(j, i, 0);
            }
        }
    }
    for (int i = 1; i <= n; i++) {
        queue<Data> Q;
        Q.push(start);
        //bool flg[1000][1000] = {{0}};
        while (!Q.empty()) {
            Data d = Q.front(); Q.pop();
            if (field[d.y][d.x] == i + '0') {
                start = Data(d.x, d.y, d.count);
                break;
            }
            //if (flg[d.y][d.x]) continue;
            //flg[d.y][d.x] = true;
            for (int j = 0; j < 4; j++) {
                int px = d.x + dx[j], py = d.y + dy[j];
                if (px < 0 || py < 0 || px >= w || py >= h) continue;
                if (field[py][px] == 'X') continue;
                Q.push(Data(px, py, d.count + 1));
            }
        }
        ans = start.count;
    }

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