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<algorithm>
#include<queue>

using namespace std;

int h, w, n;

char map[1001][1001];

int vis[1001][1001];

const int v[2][4] = { {1,0,-1,0},{0,-1,0,1} };

queue<pair<int ,int>> Pos;
queue <pair<int, pair< int, int > >> que;


int main() {
	cin >> h >> w >> n;
	for (int i = 1; i <= h; i++) {
		for (int j = 1; j <= w; j++) {
			cin >> map[i][j];
			if (map[i][j] == 'S')que.push(make_pair(0,make_pair(i,j)));
		}
	}
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= h; j++) {
			for (int k = 1; k <= w; k++) {
				if (map[j][k] - '0' == i)Pos.push(make_pair(j,k));
			}
		}
	}
	int ct = 0;
	while (Pos.size()) {
		pair<int, int > P = Pos.front();
		Pos.pop();
		while (que.size()) {
			pair<int,pair< int,int > > a = que.front();
			que.pop();
			if (vis[a.second.first][a.second.second] != 0)continue;
			vis[a.second.first][a.second.second] = a.first + 1;
			if (a.second.first == P.first&&a.second.second == P.second) {
				ct += vis[a.second.first][a.second.second];
				for (int i = 1; i <= h; i++) {
					for (int j = 1; j <= w; j++) {
						vis[i][j] = 0;
					}
				}
				while (que.size())que.pop();
				if(Pos.size())que.push(make_pair(0,make_pair(a.second.first,a.second.second)));
				ct -= 1;
				break;
			}
			for (int i = 0; i < 4; i++) {
				int px= a.second.first + v[0][i], py= a.second.second + v[1][i];
				if (1 <= px&&px <= h && 1 <= py&&py <= w&&vis[px][py] == 0 && map[px][py] != 'S'&&map[px][py]!='X') {
					que.push(make_pair(vis[a.second.first][a.second.second], make_pair(px, py)));
				}
			}
		}
	}
	cout << ct << endl;
	return 0;
}

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

using P = pair<int, int>;

constexpr int MAX_H = 1000;
constexpr int MAX_W = 1000;

int H, W, N;
int sh{-1}, sw{-1}, gh{-1}, gw{-1};
char grid[MAX_H][MAX_W + 1];
int count[MAX_H][MAX_W];

//#define OCTAS
#ifdef OCTAS
constexpr int dh[]{-1, -1, -1, 0, 0, +1, +1, +1};
constexpr int dw[]{-1, 0, +1, -1, +1, -1, 0, +1};
#else
constexpr int dh[]{-1, 0, 0, +1};
constexpr int dw[]{0, -1, +1, 0};
#endif

// CAUTION!!!
// Call init_count() first!!!
//
void init_count() {
  fill(::count[0], ::count[0] + MAX_H * MAX_W, -1);
}

int bfs(int h, int w) {
  queue<P> que;
  ::count[h][w] = 0;
  que.push(P(h, w));

  while (!que.empty()) {
    P p = que.front();
    que.pop();
    int cnt = ::count[p.first][p.second];
    if (p.first == gh && p.second == gw) {
      return cnt;
    }
    ++cnt;
    for (int i{}; i < sizeof(dh) / sizeof(int); ++i) {
      int nh = p.first + dh[i];
      int nw = p.second + dw[i];
      if (nh < 0 || nh >= H ||
          nw < 0 || nw >= W ||
          ::count[nh][nw] >= 0 ||
          grid[nh][nw] == 'X')
        continue;
      ::count[nh][nw] = cnt;
      que.push(P(nh, nw));
    }
  }

  return -1;
}

int main() {
  scanf("%d%d%d", &H, &W, &N);
  for (int h{}; h < H; ++h) {
    scanf("%s", &grid[h][0]);
    if (gh < 0) {
      for (int w{}; w < W; ++w) {
        if (grid[h][w] == 'S') {
          gh = h;
          gw = w;
        }
      }
    }
  }

  int total{};
  for (int i{0}; i < N; ++i) {
    init_count();
    sh = gh;
    sw = gw;
    for (int h{}; h < H; ++h) {
      for (int w{}; w < W; ++w) {
        if (grid[h][w] == static_cast<char>('1' + i)) {
          gh = h;
          gw = w;
          goto FOUND;
        }
      }
    }
    FOUND:
    total += bfs(sh, sw);
  }

  printf("%d\n", total);
  return 0;
}

C++: #include <cstdlib>
#include <cstdio>
#include <queue>
#include <climits>
using namespace std;

const int MAX_H = 1000;
const int MAX_W = 1000;
const int MAX_N = 10;

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

typedef struct {
	int x, y;
} node;
node makeNode(int x, int y) {
	node n = {x, y};
	return n;
}

int w, h, n;
// 入力されたフィールド (W * H)
char field[MAX_H][MAX_W];
// 各地点までのステップ数，未到達なら INT_MAX
int step[MAX_H][MAX_W];

int bfs(int startX, int startY, int goalX, int goalY) {
	queue<node> que;
	que.push(makeNode(startX, startY));
	step[startY][startX] = 0;
	while (!que.empty()) {
		node current = que.front();
		que.pop();
		if (current.x == goalX && current.y == goalY) {
			return step[goalY][goalX];
		}
		for (int i = 0; i < 4; i++) {
			int nextX = current.x + dx[i];
			int nextY = current.y + dy[i];
			if (0 <= nextX && nextX < w && 0 <= nextY && nextY < h
					&& field[nextY][nextX] != 'X' && step[nextY][nextX] == INT_MAX) {
				que.push(makeNode(nextX, nextY));
				step[nextY][nextX] = step[current.y][current.x] + 1;
			}
		}
	}
	exit(-1);
}

int main () {
	scanf("%d %d %d", &h, &w, &n);
	int startX, startY;
	// 入力しながらスタートの座標を探す
	for (int i = 0; i < h; i++) {
		scanf("%s", field[i]);
		for (int j = 0; j < w; j++) {
			if (field[i][j] == 'S') {
				startX = j;
				startY = i;
			}
		}
	}
	
	// 工場を順番に回って合計ステップを計算する
	int ans = 0;
	for (int i = 1; i <= n; i++) {
		// step を INT_MAX で初期化しながらゴールの座標を探す
		int goalX, goalY;
		for (int j = 0; j < h; j++) {
			for (int k = 0; k < w; k++) {
				step[j][k] = INT_MAX;
				if (field[j][k] == '0' + i) {
					goalX = k;
					goalY = j;
				}
			}
		}
		
		
		ans += bfs(startX, startY, goalX, goalY);
		
		startX = goalX;
		startY = goalY;
	}
	
	printf("%d\n", ans);
	return 0;
}