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 <vector>
#include <queue>
#include <algorithm>
using namespace std;

int search(int sx, int sy, int dx, int dy, vector<vector<char> > &f, int w, int h)
{
vector<bool> visit;
queue<pair<pair<int, int>, int> > q;
visit.resize(w * h, false);
q.push(make_pair(make_pair(sx, sy), 0));
while(!q.empty()) {
int x = q.front().first.first;
int y = q.front().first.second;
int cost = q.front().second;
q.pop();
if(visit[x * w + y])
continue;
visit[x * w + y] = true;
if(f[x][y] == 'X')
continue;
if(x == dx && y == dy)
return cost;
int ix[4] = {-1, 0, 0, 1};
int iy[4] = {0, -1, 1, 0};
for(int i = 0; i < 4; ++i) {
int nx = ix[i] + x;
int ny = iy[i] + y;
if(nx < 0 || ny < 0 || nx >= h || ny >= w)
continue;
q.push(make_pair(make_pair(nx, ny), cost + 1));
}
}
return -1;
}

int main() {
int h, w, n;
vector<vector<char> > f;
vector<pair<int, int> > pos;
scanf("%d%d%d", &h, &w, &n);
f.resize(h);
pos.resize(n + 1);
for(int i = 0; i < h; ++i) {
char temp[1024];
scanf("%s", temp);
f[i].resize(w);
for(int j = 0; j < w; ++j) {
f[i][j] = temp[j];
if(f[i][j] == 'S')
pos[0] = make_pair(i, j);
if('0' <= f[i][j] && f[i][j] <= '9')
pos[f[i][j] - '0'] = make_pair(i, j);
}
}
int ans = 0;
for(int i = 1; i <= n; ++i) {
int sx = pos[i - 1].first;
int sy = pos[i - 1].second;
int dx = pos[i].first;
int dy = pos[i].second;
ans += search(sx, sy, dx, dy, f, w, h);
}
printf("%d\n", ans);
return 0;
}

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

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

int H, W;
char 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 (muscle-1 == 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();
}

C++: # include <iostream>
# include <queue>
# include <cctype>
typedef std::pair<int, int> P;

const int INF = 100000;
const int MAX_H = 1000;
const int MAX_W = 1000;
const int MAX_N = 9;

int dx[4] = { 1,-1,0,0 }, dy[4] = { 0,0,1,-1 };
int h, w, n;
int d[MAX_H][MAX_W];
char ch[MAX_H][MAX_W];
P p[MAX_N + 1];

int bfs(P s, P g) {
	for (int i = 0; i<h; ++i) {
		for (int j = 0; j<w; ++j)
			d[i][j] = INF;
	}
	std::queue<P> que;
	que.push(s);
	d[s.second][s.first] = 0;
	while (!que.empty()) {
		P x = que.front(); que.pop();
		if (x == g)
			break;
		for (int i = 0; i < 4; ++i) {
			int nx = x.first + dx[i];
			int ny = x.second + dy[i];
			if (nx >= 0 && ny >= 0 && nx < w && ny < h && d[ny][nx] == INF && ch[ny][nx] != 'X') {
				que.push(P(nx, ny));
				d[ny][nx] = d[x.second][x.first] + 1;
			}
		}
	}
	return d[g.second][g.first];
}

int solve() {
	int res = 0;
	for (int i = 1; i <= n; ++i) {
		res += bfs(p[i - 1], p[i]);
	}
	return res;
}

int main() {
	std::cin >> h >> w >> n;
	for (int i = 0; i < h; ++i) {
		for (int j = 0; j < w; ++j) {
			std::cin >> ch[i][j];
			if (std::isdigit(ch[i][j])) {
				p[atoi(&ch[i][j])].first = j;
				p[atoi(&ch[i][j])].second = i;
			}
			else if (ch[i][j] == 'S') {
				p[0].first = j;
				p[0].second = i;
			}
		}
	}
	std::cout << solve() << std::endl;
	return 0;
}

C++: //#include "stdafx.h"
#include <iostream>
#include <queue>
#include <cstring>
#define INF 1000000000
using namespace std;

int row, col, n;

typedef struct point {
	int x, y;
};

char map[1000][1000];
int d[1000][1000];
int direct[4][2] = { {0,1},{0,-1},{1,0},{-1,0} };

int BFS(int &startX, int &startY, char target) {
	for (int i = 0; i < row; i++)
		for (int j = 0; j < col; j++)
			d[i][j] = INF;

	queue<point> q;
	point p;
	p.x = startX;
	p.y = startY;
	d[startX][startY] = 0;
	q.push(p);
	while (!q.empty()) {
		int nowX = q.front().x,nowY = q.front().y;
		q.pop();

		if (map[nowX][nowY] == target) {
			startX = nowX;
			startY = nowY;
			return d[nowX][nowY];
		}

		int nextX, nextY;
		for (int i = 0; i < 4; i++) {
			nextX = nowX + direct[i][0];
			nextY = nowY + direct[i][1];

			if (nextX >= 0 && nextY >= 0 && nextX < row && nextY < col && 
					map[nextX][nextY] != 'X' && d[nextX][nextY] == INF) {
				d[nextX][nextY] = d[nowX][nowY] + 1;
				p.x = nextX;
				p.y = nextY;
				q.push(p);
			}
		}
	}
	return -1;
}

int main() {
	int startX, startY, sum = 0;

	cin >> row >> col >> n;
	for (int i = 0; i < row; i++) {
		cin >> map[i];
		for (int j = 0; j < col; j++) {
			if (map[i][j] == 'S') {
				startX = i;
				startY = j;
			}
		}
	}

	for (int i = 0; i < n; i++) {
		int dis = BFS(startX, startY, i + '1');

		if (dis == -1)cout << "error" << endl;
		else sum += dis;
	}
	cout << sum;
}