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>
#include <utility>
#define MAX_H   1200
#define MAX_W   1200
#define MAX_N   10
using namespace std;

const int INF = 100000000;
typedef pair<int, int> P;

char maze[MAX_H][MAX_W];
int H, W, N;
int sx, sy;                     // スタートの座標
int gx[MAX_N], gy[MAX_N];       // ゴールの座標

int d[MAX_H][MAX_W];            // 各点までの最短距離の配列

// 移動４方向のベクトル
int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};

int bfs(int s1, int s2, int g1, int g2) {
  queue<P> que;
  // すべての点をINFで初期化
  for (int i = 0; i < MAX_H; i++) {
    for (int j = 0; j < MAX_W; j++) {
      d[i][j] = INF;
    }
  }
  // スタート地点をqueに入れ、その点の距離を0にする
  que.push(P(s1, s2));
  d[s1][s2] = 0;

  // queが空になるまでループ
  while (!que.empty()) {
    // キューの先頭を取り出す
    P p = que.front();
    que.pop();
    // 取り出してきた状態がゴールならば、探索をやめる
    if (p.first == g1 && p.second == g2) {
      break;
    }
    // 移動４方向をループ
    for (int i = 0; i < 4; i++) {
      // 移動したあとの点を(nx, ny)とする
      int nx = p.first + dx[i], ny = p.second + dy[i];

      // 移動が可能かどうかとすでに訪れたことがあるか判定
      if (0 <= nx && nx < H && 0 <= ny && ny < W && maze[nx][ny] != 'X'
          && d[nx][ny] == INF) {
        que.push(P(nx, ny));
        d[nx][ny] = d[p.first][p.second] + 1;
      }
    }
  }
  return d[g1][g2];
}

int main(void) {
  int res = 0;
  cin >> H >> W >> N;

  for (int i = 0; i < H; i++) {
    for (int j = 0; j < W; j++) {
      cin >> maze[i][j];
      if (maze[i][j] == 'S') {
        sx = i;
        sy = j;
      }
      if (isdigit(maze[i][j])) {
        gx[maze[i][j] - '0'] = i;
        gy[maze[i][j] - '0'] = j;
      }
    }
  }

  for (int i = 1; i <= N; i++) {
    if (i == 1) {
      res += bfs(sx, sy, gx[i], gy[i]);
    } else {
      res += bfs(gx[i-1], gy[i-1], gx[i], gy[i]);
    }
  }

  cout << res << endl;
  return 0;
}

C++: #include <iostream>
#include <ios>
#include <iomanip>
#include <functional>
#include <algorithm>
#include <vector>
#include <sstream>
#include <list>
#include <queue>
#include <deque>
#include <stack>
#include <string>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
#include <cstring>
#include <climits>
using namespace std;
#define XINF INT_MAX
#define INF 1<<30
#define MAXN 0x7fffffff
#define eps 1e-8
#define zero(a) fabs(a)<eps
#define sqr(a) ((a)*(a))
#define MP(X,Y) make_pair(X,Y)
#define PB(X) push_back(X)
#define PF(X) push_front(X)
#define REP(X,N) for(int X=0;X<N;X++)
#define REP2(X,L,R) for(int X=L;X<=R;X++)
#define DEP(X,R,L) for(int X=R;X>=L;X--)
#define CLR(A,X) memset(A,X,sizeof(A))
#define IT iterator
#define PI  acos(-1.0)
#define test puts("OK");
typedef long long ll;
typedef pair<int,int> PII;
typedef priority_queue<int,vector<int>,greater<int> > PQI;
typedef vector<PII> VII;
typedef vector<int> VI;
#define X first
#define Y second

char maps[1000+10][1000+10];
int dis[1000+10][1000+10];
bool vis[1000+10][1000+10];
const int dir[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
PII fac[20];
int h,w,n;

int bfs(int sx,int sy,int ex,int ey)
{
	CLR(vis,0);CLR(dis,0);
	queue<PII> Q;
	Q.push(MP(sx,sy));
	while(!Q.empty())
	{
		PII p=Q.front();Q.pop();
		if(p.X==ex && p.Y==ey)
			break;
		vis[p.X][p.Y]=1;
		REP(i,4)
		{
			int tx=p.X+dir[i][0];
			int ty=p.Y+dir[i][1];
			if(tx>=0 && tx<h && ty>=0 && ty<w && !vis[tx][ty] && maps[tx][ty]!='X')
			{
				Q.push(MP(tx,ty));
				dis[tx][ty]=dis[p.X][p.Y]+1;
			}
		}
	}
	return dis[ex][ey];
}

int main()
{
	ios::sync_with_stdio(false);
	cin>>h>>w>>n;
	REP(i,h)
		REP(j,w)
		{
			cin>>maps[i][j];
			if(maps[i][j]=='S')
			{
				fac[0]=MP(i,j);
				maps[i][j]='.';
			}
			if(isdigit(maps[i][j]))
				fac[maps[i][j]-'0']=MP(i,j);
		}
	int ans=0;
	REP(i,n)
		ans+=bfs(fac[i].X,fac[i].Y,fac[i+1].X,fac[i+1].Y);
	cout<<ans<<endl;
	return 0;
}

C++: #include<iostream>
#include<algorithm>
#include<map>
using namespace std;
#define MAX 1001

int h, w, n;
char city[MAX][MAX];
int step[10];
int direc1[4] = { -1,0,1,0 }, direc2[4] = { 0,1,0,-1 };

void dfs(char (&nowcity)[MAX][MAX], int nowstep, bool find, int nowi, int nowj, int nowpower, map<int, int> visited) {
	if (find) {
		if (step[nowpower-1] == -1) {
			step[nowpower-1] = nowstep;
		}
		else
		{
			step[nowpower-1] = min(step[nowpower-1], nowstep);
		}
		return;
	}
	if (step[nowpower] != -1) {
		if (nowstep >= step[nowpower]) {
			return;
		}
	}
	for (int i = 0; i < 4; i++) {
		if (nowi + direc1[i] >= 0 && nowi + direc1[i] < h&&nowj + direc2[i] >= 0 && nowj + direc2[i] < w) {

			if (nowcity[nowi + direc1[i]][nowj + direc2[i]] == '.') {
				if (!visited[(nowi + direc1[i]) * w + nowj + direc2[i]]) {
					visited[(nowi + direc1[i]) * w + nowj + direc2[i]]=1;
					dfs(nowcity, nowstep + 1, false, nowi + direc1[i], nowj + direc2[i], nowpower, visited);
				}	
			}
			else if (nowcity[nowi + direc1[i]][nowj + direc2[i]] >= '0'&&nowcity[nowi + direc1[i]][nowj + direc2[i]] <= '9')
			{
				int num = nowcity[nowi + direc1[i]][nowj + direc2[i]] - '0';
				if (nowpower == num) {					
					//nowcity[nowi + direc1[i]][nowj + direc2[i]] = '.';
					/*visited.clear();
					visited[(nowi + direc1[i]) * w + nowj + direc2[i]] =1;*/
					dfs(nowcity, nowstep + 1, true, nowi + direc1[i], nowj + direc2[i], nowpower,visited);
				}
				else {
					if (!visited[(nowi + direc1[i]) * w + nowj + direc2[i]]) {
						visited[(nowi + direc1[i]) * w + nowj + direc2[i]] =1;
						dfs(nowcity, nowstep + 1, false, nowi + direc1[i], nowj + direc2[i], nowpower,visited);
					}				
				}
			}
		}
	}
}



int main() {
	cin >> h >> w >> n;
	int nowi[10], nowj[10];
	
	for (int i = 0; i < h; i++)
	{
		for (int j = 0; j < w; j++)
		{
			cin >> city[i][j];
			if (city[i][j] == 'S') {
				nowi[0] = i;
				nowj[0] = j;
				city[i][j] = '.';
			}
			if (city[i][j] >= '0'&&city[i][j] <= '9') {
				nowi[city[i][j] - '0'] = i;
				nowj[city[i][j] - '0'] = j;
			}
		}
	}
	for (int i = 0; i < 10; i++) {
		step[i] = -1;
	}
	map<int, int>visited;
	for (int i = 0; i < n; i++) {
		visited.clear();
		visited[nowi[i] * w + nowj[i]] = 1;
		dfs(city, 0, false, nowi[i], nowj[i], i+1, visited);
	}
	int sum=0;
	for (int i = 0; i < n; i++) {
		sum += step[i];
	}
	cout << sum << endl;
	//system("pause");
	return 0;
}