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 <bits/stdc++.h>
using namespace std;
typedef long long ll;
const double EPS = 1e-9;
const int INF = 1e9;
const int MOD = 1e9+7;
const ll LINF = 1e18;
typedef vector<int> vint;
typedef vector<vector<int>> vvint;
typedef vector<vector<ll>> vll;
typedef pair<int, int> pint;
typedef pair<ll, ll> pll;
typedef map<int, int> mi;
typedef set<int> si;
#define VV(T) vector<vector< T > >

#define rep(i, n) REP(i, 0, n)                              // 0, 1, ..., n-1
#define REP(i, x, n) for(int i = x; i < n; i++)             // x, x + 1, ..., n-1
#define invrep(i, n) for(int i = (n)-1; i >= 0; i--)        // n-1, n-2, ..., 0
#define invREP(i, x, n) for(int i = (n)-1; i >= (x; i--)    // n-1, n-2, ..., x
#define FOREACH(x,a) for(auto& (x) : (a) )

#define ALL(v) (v).begin() , (v).end()
#define RALL(v) (v).rbegin(), (v).rend()

#define PB push_back

#define COUT(x) cout << (x) << endl
#define VECCIN(x) for(auto&youso_: (x) )cin>>youso_
#define VECCOUT(x) for(auto&youso_: (x) )cout<<youso_<<" ";cout<<endl

int H, W, N;
char maze[1000][1000];
int d[1000][1000];
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, -1, 0, 1};
pint cheese[11];

int bfs(int x){
    queue<pint> que;
    rep(i, H) rep(j, W) d[i][j] = INF;
    int sy = cheese[x].first, sx = cheese[x].second;
    int gy = cheese[x + 1].first, gx = cheese[x + 1].second;
    que.push(pint(sy, sx));
    d[sy][sx] = 0;

    while(que.size()){
        pint p =  que.front(); que.pop();
        if(p.first == gy && p.second == gx) break;
        rep(i, 4){
            int ny = p.first + dx[i], nx =  p.second + dy[i];
            if(0 <= ny && ny < H && 0 <= nx && nx < W && maze[ny][nx] != 'X' && d[ny][nx] == INF){
                d[ny][nx] = d[p.first][p.second] + 1;
                que.push(pint(ny, nx));
            }
        }
    }
    return d[gy][gx];
}

int main(){
    cin >> H >> W >> N;
    rep(i, H) rep(j, W){
        cin >> maze[i][j];
        if(maze[i][j] == 'S'){
            cheese[0] = pint(i, j);
        }
        if(maze[i][j] != 'S' && maze[i][j] != 'X' && maze[i][j] != '.') cheese[maze[i][j] - '0'] = pint(i, j);  
    }
    int ans = 0;
    rep(i, N) ans += bfs(i);
    COUT(ans);
}

C++: #include <bits/stdc++.h>
#define rep(i,n) for(int i = 0; i < n; i++)
#define fi first
#define se second

using namespace std;

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

int main() {

  int H, W, N;
  cin >> H >> W >> N;

  vector< vector<char> > field(H, vector<char> (W));
  vector< pair<int, int> > factory(10, make_pair(-1, -1));
  
  rep(h, H) {
    rep(w, W) {
      cin >> field[h][w];
      if(field[h][w] == 'S') factory[0] = (make_pair(h, w));
      if(field[h][w] == '1') factory[1] = (make_pair(h, w));
      if(field[h][w] == '2') factory[2] = (make_pair(h, w));
      if(field[h][w] == '3') factory[3] = (make_pair(h, w));
      if(field[h][w] == '4') factory[4] = (make_pair(h, w));
      if(field[h][w] == '5') factory[5] = (make_pair(h, w));
      if(field[h][w] == '6') factory[6] = (make_pair(h, w));
      if(field[h][w] == '7') factory[7] = (make_pair(h, w));
      if(field[h][w] == '8') factory[8] = (make_pair(h, w));
      if(field[h][w] == '9') factory[9] = (make_pair(h, w));
    }
  }

  int res = 0;
  rep(cur, N) {
    int sh = factory[cur].fi;
    int sw = factory[cur].se;
    int gh = factory[cur+1].fi;
    int gw = factory[cur+1].se;

    queue< pair<int, int> > que;
    vector< vector<int> > dist(H, vector<int> (W, -1));
    dist[sh][sw] = 0;
    que.push({sh, sw});

    while(!que.empty()) {
      int vh = que.front().fi;
      int vw = que.front().se;
      que.pop();

      rep(dir, 4) {
        int nvh = vh + dy[dir];
        int nvw = vw + dx[dir];

        if(nvh < 0) continue;
        if(nvw < 0) continue;
        if(nvh >= H) continue;
        if(nvw >= W) continue;
        if(dist[nvh][nvw] != -1) continue;
        if(field[nvh][nvw] == 'X') continue;

        dist[nvh][nvw] = dist[vh][vw]+1;
        que.push({nvh, nvw});
      }
    }
    res += dist[gh][gw];
  }
  
  cout << res << endl;
}

C++: #include<stdio.h>
#include<iostream>
#include<queue>
using namespace std;
typedef pair<int, int> P;
int n, m, ci,sum1;
char Map[1010][1010];
queue<P>q;
struct node {
	int x;
	int y;
}node[10];
void bfs(int sx, int sy, int ex, int ey)
{
	sum1 = 0;
	int dx[] = { 0,0,1,-1 };
	int dy[] = { 1,-1,0,0 };
	while (!q.empty())
		q.pop();
	q.push(P(sx, sy));
	while (!q.empty())
	{
		int l = q.size();
		sum1++;
		while (l)
		{
			l--;
			P p = q.front(); q.pop();
			for (int i = 0; i < 4; i++)
			{
				int nx = p.first + dx[i];
				int ny = p.second + dy[i];
				if (nx < n&&nx >= 0 && ny >= 0 && ny < m)
				{
					if (ny == ey&&nx == ex)
						return;
					else if (Map[nx][ny] != 'X')
					{
						q.push(P(nx, ny));
					}
				}
			}
		}
	}
}
int main()
{
	//freopen("C:\\Users\\国民党\\Desktop\\text.txt", "r", stdin);
	int sum = 0;
	scanf("%d%d%d", &n, &m, &ci);
	for (int i = 0; i < n; i++)
	{
		scanf("%s", &Map[i]);
		for (int j = 0; j < m; j++)
		{
			if (Map[i][j] == 'S')
			{
				node[0].x = i;
				node[0].y = j;
			}
			else if (Map[i][j] <= '9'&&Map[i][j] >= '1')
			{
				node[Map[i][j] - 48].x = i;
				node[Map[i][j] - 48].y = j;
			}
		}
	}
	if (ci == 0)
		printf("0\n");
	else
	{
		for (int i = 0; i < ci; i++)
		{
			bfs(node[i].x, node[i].y, node[i + 1].x, node[i + 1].y);
			sum += sum1;
		}
		printf("%d\n", sum);
	}
	return 0;
}