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<queue>
using namespace std;
typedef pair<int, int> P;
const int MAX_N = 1000;
const int MAX_M = 1000;
const int MAX_T = 9;
const int INF = 100000000;
int n, m, t;
int sx, sy;
int ans = 0;
char field[MAX_N][MAX_M];
int d[MAX_N][MAX_M];
P factory[MAX_T];
int dx[4] = {0, -1, 0, 1}, dy[4] = {-1, 0, 1, 0};

//从当前起点&#24320;始，&#23547;找第num个&#22902;酪 
int bfs(int x, int y, int num){
	int gx = factory[num].first;
	int gy = factory[num].second;
	queue<P> que;
	for(int i = 0; i < n; i++){
		for(int j = 0; j < m; j++){
			d[i][j] = INF;
		}
	}
	d[x][y] = 0;
	que.push(P(x,y));
	
	while(que.size()){
		P p = que.front();
		que.pop();
		int x = p.first;
		int y = p.second;
		if(x == gx && y == gy){
			break;
		}
		for(int i = 0; i < 4; i++){
			int nx = x + dx[i], ny = y + dy[i];
			if(nx >= 0 && nx < n && ny >= 0 && ny < m && field[nx][ny] != '#' && d[nx][ny] == INF){
				d[nx][ny] = d[x][y] + 1;
				que.push(P(nx, ny));
			}
		}
	}
	
	return d[gx][gy];
}

void solve(){
	cin >> n >> m >> t;
	for(int i = 0; i < n; i++){
		for(int j = 0; j < m; j++){
			cin >> field[i][j];
			if(field[i][j] == 'S'){
				factory[0] = P(i, j);
			}
			if(field[i][j] >= '1' && field[i][j] <= '9'){
				int index = field[i][j] - '0';
				factory[index] = P(i, j);
			}
		}
	}
	
	for(int i = 0; i < t; i++){
		int x = factory[i].first;
		int y = factory[i].second;
		cout << x << " " << y << "\n";
	}
	int ans = 0;
	
	for(int i = 0; i < t; i++){
		int x = factory[i].first;
		int y = factory[i].second;
		ans += bfs(x, y, i + 1);
	}
	cout << ans;
}

int main(){
	solve();
}

C++: #include <cstdio>
#include <algorithm>
#include <queue>

using namespace std;

typedef pair<int, int> P;

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

char maze[MAX_H][MAX_W + 1];

int H, W, N;
int si, sj;
int gi[MAX_N + 1], gj[MAX_N + 1];
int d[MAX_H][MAX_W];

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

int bfs(int goalNum)
{
  queue<P> que;
  int cgi = gi[goalNum], cgj = gj[goalNum];

  for (int i = 0; i < H; i++)
    for (int j = 0; j < W; j++)
      d[i][j] = INF;

  que.push(P(si, sj));
  d[si][sj] = 0;

  while (que.size()) {
    P p = que.front(); que.pop();

    if (p.first == cgi && p.second == cgj) break;

    for (int i = 0; i < 4; i++) {
      int ni = p.first + dx[i], nj = p.second + dy[i];

      if (0 <= ni && ni < H && 0 <= nj && nj < W && maze[ni][nj] != 'X' && d[ni][nj] == INF) {
        que.push(P(ni, nj));
        d[ni][nj] = d[p.first][p.second] + 1;
      }
    }
  }

  return d[cgi][cgj];
}

int solve()
{
  int res = 0;
  for (int i = 1; i <= N; i++) {
    // printf("%d:(%d, %d) => ", i, si, sj);
    res += bfs(i);
    si = gi[i]; sj = gj[i];
    // printf("(%d, %d):%d\n", si, sj, res);
  }
  return res;
}

int main()
{
  scanf("%d %d %d", &H, &W, &N);
  for (int i = 0; i < H; i++) {
    scanf("%s", maze[i]);
    maze[i][W] = 0;

    for (int j = 0; j < W; j++) {
      if ('0' < maze[i][j] && maze[i][j] <= '9') {
        gi[maze[i][j] - '0'] = i;
        gj[maze[i][j] - '0'] = j;
      }
      if (maze[i][j] == 'S') {
        si = i;
        sj = j;
      }
    }
  }

  printf("%d\n", solve());
}

C++: #include<bits/stdc++.h>
using namespace std;

using i64 = long long int;

struct Node{
    int x, y, cost, hp;
};

char field[1003][1003];
int mini[1003][1003][11];

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

int main(){
    int h, w, n;
    cin >> h >> w >> n;

    int sx, sy;
    for(int i=0;i<h;++i){
        for(int j=0;j<w;++j){
            cin >> field[i][j];
            if(field[i][j] == 'S'){
                sx = j;
                sy = i;
            }
        }
    }

    for(int i=0;i<h;++i){
        for(int j=0;j<w;++j){
            for(int k=0;k<=n+1;++k)
                mini[i][j][k] = INT_MAX;
        }
    }

    mini[sy][sx][1] = 0;
    queue<Node> que;
    que.push((Node){sx, sy, 0, 1});
    while(!que.empty()){
        Node curr = que.front(); que.pop();
        if(curr.hp == n + 1){
            cout << curr.cost << endl;
            break;
        }
        for(int d=0;d<4;++d){
            int nx = curr.x + dx[d], ny = curr.y + dy[d], newcost = curr.cost + 1;
            if(nx < 0 || nx >= w)continue;
            if(ny < 0 || ny >= h)continue;
            if(field[ny][nx] == 'X')continue;
            int nhp = curr.hp;
            if(field[ny][nx] == curr.hp + '0')nhp++;
            if(newcost >= mini[ny][nx][nhp])continue;
            mini[ny][nx][nhp] = newcost;
            que.push((Node){nx, ny, newcost, nhp});
        }
    }

    return 0;
}

C++: #include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <utility>
#include <queue>

using namespace std;

const int DR[] = {0, 0, 1, -1};
const int DC[] = {1, -1, 0, 0};
struct Tag {
    int r, c, distance;
    Tag() {}
    Tag(int r, int c, int d) : r(r), c(c), distance(d) {}
};
bool visited[1000][1000];

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

    int H, W, N;
    cin >> H >> W >> N;
    vector<string> field(H);
    pair<int,int> cur;
    for(int i = 0; i < H; ++i) {
        cin >> field[i];
        size_t spos = field[i].find('S');
        if(spos != string::npos) {
            cur = make_pair(i, spos);
        }
    }
    int ans = 0;
    for(int target = 1; target <= N; ++target) {
        for(int i = 0; i < H; ++i) {
            fill_n(visited[i], W, false);
        }
        Tag route;
        queue<Tag> q;
        q.push(Tag(cur.first, cur.second, 0));
        while(!q.empty()) {
            Tag t = q.front();
            q.pop();
            for(int i = 0; i < 4; ++i) {
                int nr = t.r + DR[i];
                int nc = t.c + DC[i];
                if(0 <= nr && nr < H && 0 <= nc && nc < W) {
                    if(field[nr][nc] != 'X' && !visited[nr][nc]) {
                        visited[nr][nc] = true;
                        if(field[nr][nc] == '0'+target) {
                            route = Tag(nr, nc, t.distance+1);
                            goto found;
                        }
                        q.push(Tag(nr, nc, t.distance+1));
                    }
                }
            }
        }
found:
        ans += route.distance;
        cur = make_pair(route.r, route.c);
    }

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