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;

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 + 1];
// 各地点までのステップ数，未到達なら -1
int step[MAX_H][MAX_W + 1];

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[current.y][current.x];
		}
		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] == -1) {
				que.push(makeNode(nextX, nextY));
				step[nextY][nextX] = step[current.y][current.x] + 1;
			}
		}
	}
	return -1;
}

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

C++: #include <iostream>
#include <algorithm>
#include <queue>
#include <cstdio>
#include <string>
using namespace std;
#define rep(i,n) for(int i=0;i<(n);i++)
#define reps(i,f,n) for(int i=(f);i<(n);i++)
#define fi first
#define se second
static const int INF = 1e9;
int dx[4] = {1, 0, 0, -1};
int dy[4] = {0, 1, -1, 0};
string board[1001];//??\?????¨??????
int d[1001][1001];//???????????¢?´¢???????????¨???????????§??????????????¢?????\????????????
int h, w, n;
pair<int, int> point[10];//fi=y??§?¨? se=x??§?¨?
int ans = 0;
bool flag;
//???????????¢?´¢
void bfs(void){
	rep(i, n){//??????????????¨??´?????????
		int starty = point[i].fi, startx = point[i].se;//start
		int endy = point[i + 1].fi, endx = point[i + 1].se;//end
		queue<pair<int, int> > q;
		q.push(make_pair(starty, startx));//start???????????\??????
		rep(i, h) rep(j, w) d[i][j] = INF;//?????????
		d[starty][startx] = 0;
		flag = false;
		while(!q.empty()){
			pair<int, int> now;
			now = q.front(); q.pop();
			rep(j, 4){//4??????????????????
				int y = now.fi + dy[j];
				int x = now.se + dx[j];
				if(y < 0 || h <= y || x < 0 || w <= x) continue;//?????????
				if(d[y][x] == INF && board[y][x] != 'X'){
					d[y][x] = d[now.fi][now.se] + 1;//???????????¢????¨????
					q.push(make_pair(y, x));
				}
				if(y == endy && x == endx){
					flag = true;
					ans += d[y][x];//?????¢????¶?????????????
					break;
				}
			}
			if(flag == true) break;
		}
	}
	return;
}

int main(void){
	cin >> h >> w >> n;
	rep(i, h){
		cin >> board[i];
	}

	//start????????¨??????????????´?????????????±?????????????
	rep(i, h) rep(j, w){
		if(board[i][j] == 'S'){
			point[0].fi = i; point[0].se = j;
		}else if ('1' <= board[i][j] && board[i][j] <= '9'){
			int tmp = board[i][j] - '0';
			point[tmp].fi = i; point[tmp].se = j;
		}
	}
	bfs();
	cout << ans << endl;
	return 0;
}

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

typedef pair<int,int> P;

int H,W,N;
int ans = 0;
int dx[] = {1,-1,0,0}, dy[] = {0,0,1,-1};
string map[1000];

P sg[20] = {};	// 要素番号＝数字(０はスタート地点)
				// P(x,y)

int main(void)
{

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

			if(c == 'S')
				sg[0] = P(j,i);
			else if(c >= '0' && c <= '9')
				sg[c-'0'] = P(j,i);
		}
		cin.get();
	}

//	for(int i = 0; i <= N; i++)
//		cout << sg[i].first << ' ' << sg[i].second << endl;

	int ans = 0;
	for(int now = 0; now < N; now++){
		queue<P> que;
		int **d;	d = new int *[H];	for(int aa = 0; aa < H; aa++){d[aa] = new int [W]; for(int bb = 0; bb < W; bb++)d[aa][bb] = 0;}
		que.push(sg[now]);
		d[sg[now].second][sg[now].first] = 0;

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

			if(sg[now+1] == pos){
//				cout << d[pos.second][pos.first] << ' ' << sg[now+1].first << ',' << sg[now+1].second << endl;
				ans += d[pos.second][pos.first];
				break;
			}

			for(int i = 0; i < 4; i++){
				int nx = pos.first + dx[i];
				int ny = pos.second+ dy[i]; 
				if(nx < 0 || ny < 0 || nx >= W || ny >= H)
					continue;
				if(map[ny][nx] == 'X' )
					continue;

				if(d[ny][nx] == 0){
					d[ny][nx] = d[pos.second][pos.first] + 1;
					que.push(P(nx,ny));
				}
			}
		}
		for(int aa = 0; aa < H; aa++)
			delete[]d[aa];
		delete [] d;
		

	}

	cout << ans << endl;
}

C++: #include <iostream>
#include <queue>
#define min(x,y) ((x)<(y)?(x):(y))
#define INFI 3000

using namespace std;
typedef pair<int, int> P;

int Strength = 1;
char Maps[1010][1010];
int dist[1010][1010];
int H, W, N;
int hor[] = {1,0,-1,0};
int ver[] = {0,-1,0,1};
int ans;


void clear();
void show();
P bfs(int cheese,P n);

int main(void) {
    cin>>H>>W>>N;
    P s,e;
    for (int i = 0; i<H; i++)
        cin>>Maps[i];
    for (int i = 0; i<H; i++)
        for (int j = 0; j<W; j++)
            if (Maps[i][j]=='S') s.first = i, s.second = j;
    
    
    for (int i = 1; i<=N; i++) {
        clear();
        s = bfs(i, s);
    }
    
    cout<<ans<<endl;
    return 0;
}

P bfs(int cheese,P n) {
    queue<P> que;
    que.push(n);
    dist[n.first][n.second] = 0;
    
    P top;
    while (que.size()) {
        top = que.front();
        if (Maps[top.first][top.second]-'0'==cheese) {
            ans += dist[top.first][top.second];
            break;
        }
        
        que.pop();
        for (int i = 0; i<4; i++) {
            int nv = top.first+ver[i], nh = top.second+hor[i];
            if (nv>=0 && nv<H && nh>=0 && nh<W && dist[nv][nh]==INFI && Maps[nv][nh]!='X') {
                que.push(P(nv,nh));
                dist[nv][nh] = min(dist[nv][nh], dist[top.first][top.second]+1);
            }
        }
    }
    return top;
}

void clear() {
    for (int i = 0; i<H; i++)
        for (int j = 0; j<W; j++)
            dist[i][j] = INFI;
}