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 <stdlib.h>
#include <queue>
#include <cstring>
#define MAX_NUM 1010
using namespace std;
int H, W, N;
bool flag[MAX_NUM][MAX_NUM] = {false};                            //??是否已遍??
int dir[4][2] = { {1, 0}, { -1, 0}, {0, 1}, {0, -1} };

class Node {
  public:
    Node();
    Node(int x, int y, int step);
    ~Node();
    int x;
    int y;
    int step;
};

Node::Node() {
}

Node::Node(int x, int y, int step) {
    this->x = x;
    this->y = y;
    this->step = step;
}

Node::~Node() {
}

int BFS(char map[][MAX_NUM], int sx, int sy, int ex, int ey) {
    queue<Node> que;                                                  //第一次出?Memory Limit Exceeded,一定不能使用new来?行?建
    Node node(sx, sy, 0);
    que.push(node);
    flag[sx][sy] = true;                                              //将遍?的?点?置?true

    while(!que.empty()) {
        Node cur = que.front();
        que.pop();

        if(cur.x == ex && cur.y == ey) {
            return cur.step;

        } else {
            for(int i = 0; i < 4; i++) {
                int k = cur.x + dir[i][0];
                int v = cur.y + dir[i][1];

                if(k >= 0 && k < H && v >= 0 && v < W && map[k][v] != 'X' && !flag[k][v]) { //将可到?并且尚未遍?的?点加入?列
                    Node temp(k, v, cur.step + 1);
                    que.push(temp);
                    flag[k][v] = true;
                }
            }
        }
    }

    return -1;
}

int main() {
    int sx, sy, arr[10][2];
    char map[MAX_NUM][MAX_NUM];

    if(cin >> H >> W >> N && H && W) {
        for(int i = 0; i < H; i++) {
            for(int j = 0; j < W; j++) {
                cin >> map[i][j];

                if(map[i][j] == 'S') {
                    map[i][j] = '.';
                    sx = i;
                    sy = j;
                }

                if(isdigit(map[i][j])) {
                    int index = map[i][j] - '0';
                    arr[index][0] = i;
                    arr[index][1] = j;
                }
            }
        }

        arr[0][0] = sx;
        arr[0][1] = sy;
        int res = 0;

        for(int i = 0; i + 1 <= N; i++) {
            memset(flag, false, sizeof(flag));
            res += BFS(map, arr[i][0], arr[i][1], arr[i + 1][0], arr[i + 1][1]);
        }

        cout << res << endl;
    }

    return 0;
}

C++: #include "bits/stdc++.h"

using namespace std;

//#define int long long

#define FOR(i, a, b) for (int i = (a); i < (b); i++)
#define REP(i, n) for (int i = 0; i < (n); i++)

#define pb push_back
#define VDEL(v, n) v.erase(v.begin() + (n))
#define ALL(v) v.begin(), v.end()

#define INTMAX 2147483647
#define INF 200000000
#define TINT(str) atoi(str.c_str())
#define TSTR(num) to_string(num)

typedef long long ll;
typedef pair<int, int> PII;
typedef vector<int> VI;
typedef vector<vector<int>> VII;

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

PII goal[10];
char k[1000][1000];
int fx, fy;
int H,W;

int BFS(int x, int y)
{
    VII cost;
    cost = VII(H, VI(W, INT_MAX));

    cost[fx][fy] = 0;

    queue<PII> q;

    q.push(make_pair(fx, fy));

    while(!q.empty())
    {
        PII now = q.front();
        q.pop();
        int nx = now.first;
        int ny = now.second; 

        REP(i, 4)
        {
            if(nx + dx[i] >= H ||
            nx + dx[i] < 0) continue;
            if(ny + dy[i] >= W || 
            ny + dy[i] < 0) continue;

            if(k[nx + dx[i]][ny + dy[i]] != 'X')
            {
                if(nx + dx[i] == x &&
                    ny + dy[i] == y)
                {
                    return cost[nx][ny] + 1;
                }

                if(cost[nx + dx[i]][ny + dy[i]] > 
                cost[nx][ny])
                {
                    cost[nx + dx[i]][ny + dy[i]] =
                        cost[nx][ny] + 1;
                    q.push(make_pair(nx + dx[i], ny + dy[i]));
                }
            }
            else continue;
        }
    }

    return -1;
}

signed main()
{
    int N;
    cin >> H >> W >> N;

    char str[1001];
    REP(h, H)
    {
        scanf("%s", str);
        REP(w, W)
        {
            k[h][w] = str[w];
            if(k[h][w] == 'S')
            {
                fx = h;
                fy = w;
            }
            if(k[h][w] != '.' &&
                k[h][w] != 'X')
            {
                goal[k[h][w] - '1'] = make_pair(h, w);
            }
        }
    }
    int ans = 0;

    REP(i, N)
    {
        ans += BFS(goal[i].first, goal[i].second);
        fx = goal[i].first;
        fy = goal[i].second;
    }

    cout << ans << endl;

    return 0;
}