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 time;

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;
                time += 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() {
    time = 0;
    bfs();
    printf("%d",time);
}

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 <vector>
#include <string>
#include <queue>
using namespace std;
int h, w, n;
string field[1000];
bool visited[10][1000][1000];
struct state {
	int i, j, d;
};

bool out(int i, int j) {
	return i < 0 || h <= i || j < 0 || w <= j;
}

int search(int i, int j, int num) {
	if(num == n + 1) return 0;
	int sum = 0;
	queue<state> q;
	q.push({ i, j, 0 });
	while(!q.empty()) {
		state s = q.front(); q.pop();
		if(out(s.i, s.j) || field[s.i][s.j] == 'X' || visited[num][s.i][s.j]) continue;
		if(field[s.i][s.j] == '0' + num) {
			sum += s.d;
			break;
		}
		visited[num][s.i][s.j] = true;
		int dir[] = { 1, 0, -1, 0, 1 };
		for(int k = 0; k < 4; k++) {
			if(!visited[num][s.i + dir[k]][s.j + dir[k + 1]])
				q.push({ s.i + dir[k], s.j + dir[k + 1], s.d + 1 });
		}
	}
	for(int ii = 0; ii < h; ii++) {
		for(int jj = 0; jj < w; jj++) {
			if(field[ii][jj] == '0' + num) {
				sum += search(ii, jj, num + 1);
			}
		}
	}
	return sum;
}


int main() {
	cin >> h >> w >> n;
	for(int i = 0; i < h; i++) {
		cin >> field[i];
	}
	for(int i = 0; i < h; i++) {
		for(int j = 0; j < w; j++) {
			if(field[i][j] == 'S') {
				cout << search(i, j, 1) << endl;
				return 0;
			}
		}
	}

}

C++: #include<iostream>
#include<queue>
#include<utility>
#define INF 5000000
using namespace std;

char fl[1010][1010];

int bfs(int sx, int sy, int gx, int gy, int mx, int my) {
	typedef pair<int, int>P;
	int d[1010][1010];
	int dx[4] = { 1,0,-1,0 }, dy[4] = { 0,1,0,-1 };

	for (int i = 0;i < mx;i++)
		for (int j = 0;j < my;j++)d[i][j] = INF;

	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 + dx[i], ny = p.second + dy[i];

			if (0 <= nx&&nx < my && 0 <= ny&&ny < mx&&fl[nx][ny] != 'X'&&d[nx][ny] != INF) {
				que.push(P(nx, ny));
				d[nx][ny] = d[p.first][p.second] + 1;
			}
		}
	}
	return d[gx][gy];
}

int main() {
	int h, w, n;
	cin >> h >> w >> n;
	int al = 0;
	for (int i = 0;i < h;i++) {
		for (int j = 0;j < w;j++) { cin >> fl[i][j]; 
		}
	}
	char a[10] = { 'S','1','2','3','4','5','6','7','8','9' };
	for (int i = 0;i < n;i++) {
		int sx, sy;
		int gx, gy;
		for (int j = 0;j < h;j++) {
			for (int k = 0;k < w;k++) {

				if (fl[j][k]== a[i]) {
					sx = j;
					sy = k;
				}
				if (fl[j][k]== a[i+1]) {
					gx = j;
					gy = k;
				}
			}
		}

		al += bfs(sx, sy, gx, gy, h,w);
	}
	cout << al << endl;
	return 0;
}

C++: #include <bits/stdc++.h>
#define rep(i,a,b) for(int i=a;i<(b);++i)
#define erep(i,a,b) for(int i=a;i<=(int)(b);++i)
#define per(i,a,b) for(int i=(b);i>(a);--i)
#define eper(i,a,b) for(int i=((int)(a));i>=b;--i)
#define pb push_back
#define mp make_pair
#define INF (1<<28)-1
#define MOD 1000000007
#define all(x) (x).begin(),(x).end()
using namespace std;
typedef long long ll;
typedef pair<int,int> Pii;
template<class T>bool chmax(T &a, const T &b) { if (a<b) { a = b; return 1; } return 0; }
template<class T>bool chmin(T &a, const T &b) { if (b<a) { a = b; return 1; } return 0; }
int dy[]={0, 0, 1, -1};
int dx[]={1, -1, 0, 0};
int gcd(int a,int b){return b?gcd(b,a%b):a;}
int lcm(int a,int b){return a/gcd(a, b)*b;}

int h, w, n, sx, sy, d[1005][1005];
char g[1005][1005];

int bfs(int x, int y, int cnt) {
    queue<Pii> que;
    que.push(mp(x, y));
    rep(i, 0, h) rep(j, 0, w) d[i][j] = INF;
    d[x][y] = 0;
    int gx, gy;
    while (!que.empty()) {
        Pii p = que.front(); que.pop();
        if (g[p.first][p.second] == (char)('0'+cnt)) {
            gx = sx = p.first, gy = sy = p.second;
            break;
        }
        rep(i, 0, 4) {
            int nx = p.first + dx[i], ny = p.second + dy[i];
            if (0 <= nx && nx < h && 0 <= ny && ny < w && g[nx][ny] != 'X' && d[nx][ny] == INF) {
                que.push(mp(nx, ny));
                d[nx][ny] = d[p.first][p.second] + 1;
            }
        }
    }
    return d[gx][gy];
}

int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);
    cin >> h >> w >> n;
    rep(i, 0, h) rep(j, 0, w) {
        cin >> g[i][j];
        if (g[i][j] == 'S') sx = i, sy = j;
    }
    int ans = 0;
    rep(i, 0, n) {
        ans += bfs(sx, sy, i+1);
    }
    cout << ans << endl;
    return 0;
}