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;

#define TEMP_T template<typename T>
TEMP_T void sort(T& v){ sort(v.begin(), v.end()); }
TEMP_T void revs(T& v){ reverse(v.begin(), v.end()); }
TEMP_T void uniq(T& v){ sort(v); v.erase(unique(v.begin(), v.end())); }
TEMP_T void show(T& v, char delim=' ', char end='\n'){ for(int i=0; i<v.size()-1; i++) cout << v[i] << delim; cout << v[v.size()-1] << end; }
TEMP_T T    cums(T& v){ T r; r.push_back(v[0]); for(int i=1; i<v.size(); i++) r.push_back(r[i-1] + v[i]); return r; }
TEMP_T void maxe(T& v, T m){ v = max(v, m); }
TEMP_T void mine(T& v, T m){ v = min(v, m); }

static inline int in(){ int x; scanf("%d", &x); return x; }

struct Edge {
  int f, t, c;
  Edge(int f, int t, int c) : f(f), t(t), c(c) {}
  bool operator<(const Edge& e) const { return c > e.c; }
};
typedef vector<Edge> Vertex;
typedef vector<Vertex> Graph;

struct Solver {
  Solver(int w, int h, int n) : w(w), h(h), G(w * h), pos(n + 1) {}
  int read_input(){
    for (int i = 0; i < h; i++){
      string s;
      cin >> s;
      field.push_back(s);
    }
    for (int y = 0; y < h; y++){
      for (int x = 0; x < w; x++){
        if (field[y][x] == 'X') continue;
        for (int d = 0; d < 4; d++){
          static const int dx[] = {1, -1, 0, 0};
          static const int dy[] = {0, 0, 1, -1};
          int ny = y + dy[d];
          int nx = x + dx[d];
          if (nx < 0 || nx >= w || ny < 0 || ny >= h) continue;
          if (field[ny][nx] == 'X') continue;
          G[y * w + x].push_back(Edge(y * w + x, ny * w + nx, 1));
        }
        if (isdigit(field[y][x])){
          pos[field[y][x] - '0'] = y * w + x;
        }
        if (field[y][x] == 'S'){
          pos[0] = y * w + x;
        }
      }
    }
    return (0);
  }
  int solve(){
    int sum = 0;
    for (int i = 0; i < pos.size() - 1; i++){
      sum += get_path_len(pos[i], pos[i + 1]);
    }
    return sum;
  }
  int get_path_len(int f, int t){
    int n = G.size();
    priority_queue<Edge> pQ;
    set<int> v;
    pQ.push(Edge(-1, f, 0));
    while (!pQ.empty()){
      Edge e = pQ.top();
      pQ.pop();
      if (e.t == t) return e.c;
      if (v.find(e.t) != v.end()) continue;
      v.insert(e.t);
      for (int i = 0; i < G[e.t].size(); i++){
        pQ.push(Edge(e.t, G[e.t][i].t, e.c + G[e.t][i].c));
      }
    }
    return -1;
  }

  vector<string> field;
  vector<int> pos;
  int w, h;
  Graph G;
};

int main()
{
  int w, h, n;
  h = in();
  w = in();
  n = in();
  Solver solver(w, h, n);
  solver.read_input();
  printf("%d\n", solver.solve());

  return (0);
}

C++: #include <iostream>
#include <stdlib.h>
#include <queue>
#include <cstring>
#include <cstdio>
#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} };
char map[MAX_NUM][MAX_NUM];

struct Node {
    int x;
    int y;
    int step;

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

int BFS(int sx, int sy, int ex, int ey) {
    queue<Node> que;
    que.push(Node(sx, sy, 0));
    flag[sx][sy] = true;

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

        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]) {
                continue;
            }

            que.push(Node(k, v, cur.step + 1));
            flag[k][v] = true;

            if(k == ex && v == ey) {
                return cur.step + 1;
            }
        }
    }

    return -1;
}

int main() {
    int sx, sy, arr[10][2];
    freopen("data.in", "r", stdin);
    freopen("data.out", "w", stdout);

    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(arr[i][0], arr[i][1], arr[i + 1][0], arr[i + 1][1]);
        }

        cout << res << endl;
    }

    return 0;
}

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

int main();
int bfs();
void slove();
int N,M;
char num;
char maze[100][101]; //迷路を表す文字列の配列
int sx,sy; //スタートの座標
int gx,gy; //ゴールの座標
int d[100][101]; //各地点までの最短距離の配列
//移動4方向のベクトル
int dx[4]={1,0,-1,0},dy[4]={0,1,0,-1};
const int INF=100000000;

//状態を表すクラスpairの場合、typedefしておくと便利
typedef pair<int,int> P;

//入力
int main(){
  cin >> N;
  cin >> M;
  cin >> num;
  for(int i=0;i<N;i++){
    for(int j=0;j<M;j++){
      cin >> maze[i][j];
      if(maze[i][j]=='S'){
	sx=i;
	sy=j;
      }
      else if(maze[i][j]==num){
	gx=i;
	gy=j;
      }
    }
  }
  slove();
  return  0;
}

//(sx,sy)から(gx,gy)への最短距離を求める
//たどり着けないとINF
int bfs(){
  queue<P> que;

  //すべての点をINFで初期化
  for(int i=0;i<N;i++)
    for(int j=0;j<M;j++) d[i][j]=INF;
  
  //スタート地点をキューに入れ、その点の距離を0にする
  que.push(P(sx,sy));
  d[sx][sy]=0;
  
  //キューが空になるまでループ
  while (que.size()){
    
    //キューの先頭を取り出す
    P p=que.front();que.pop();
    
    //取り出してきた状態がゴールなら探索をやめる
    if(p.first==gx && p.second==gy) break;
    
    //移動4方向をループ
    for(int i=0;i<4;i++){
      
      //移動した後の点を(nx,ny)とする
      int nx=p.first+dx[i],ny=p.second+dy[i];
      
      //移動が可能かの判定とすでに訪れたことがあるかの判定(d[nx][ny]!=INFなら訪れたことがある)
      if(0<=nx && nx<N && 0<=ny && ny<M && maze[nx][ny]!='#' && d[nx][ny]==INF){
	
	//移動できるならキューに入れ、その点の距離をpからの距離+1で確定する
	que.push(P(nx,ny));
	d[nx][ny]=d[p.first][p.second]+1;
      }
    }
  }
  return d[gx][gy];
}

void slove(){
  int res=bfs();
  printf("%d\n",res);
}