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 <cstring>
#include <utility>

using namespace std;

char a[1003][1003];
int r, c;

int bfs (int n)
{
    bool done[1003][1003];
    int cost[1003][1003];
    queue<pair<int, int>> que;
    memset(done, false, sizeof(done));
    done[r][c]=true;
    cost[r][c]=0;
    que.push({r,c});
    while (1)
    {
        r=que.front().first, c=que.front().second;
        que.pop();
        if (!done[r][c+1])
        {
            done[r][c+1]=true;
            if (a[r][c+1]-'0'==n) { c++; cost[r][c]=cost[r][c-1]+1; return cost[r][c]; }
            if (a[r][c+1]!='X') { cost[r][c+1]=cost[r][c]+1; que.push({r, c+1}); }
        }
        if (!done[r][c-1])
        {
            done[r][c-1]=true;
            if (a[r][c-1]-'0'==n) { c--; cost[r][c]=cost[r][c+1]+1; return cost[r][c]; }
            if (a[r][c-1]!='X') { cost[r][c-1]=cost[r][c]+1; que.push({r, c-1}); }
        }
        if (!done[r+1][c])
        {
            done[r+1][c]=true;
            if (a[r+1][c]-'0'==n) { r++; cost[r][c]=cost[r-1][c]+1; return cost[r][c]; }
            if (a[r+1][c]!='X') { cost[r+1][c]=cost[r][c]+1; que.push({r+1, c}); }
        }
        if (!done[r-1][c])
        {
            done[r-1][c]=true;
            if (a[r-1][c]-'0'==n) {r--; cost[r][c]=cost[r+1][c]+1; return cost[r][c]; }
            if (a[r-1][c]!='X') { cost[r-1][c]=cost[r][c]+1; que.push({r-1, c}); }
        }
    }
}

int main()
{
    int h, w, n, ans=0;
    cin>>h>>w>>n;
    memset(a, 'X', sizeof(a));
    for (int i=1; i<=h; i++) for (int j=1; j<=w; j++) { cin>>a[i][j]; if (a[i][j]=='S') { r=i; c=j; } }
    for (int i=1; i<=n; i++) ans+=bfs(i);
    cout<<ans<<'\n';
    return 0;
}

C++: #include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
#include <cstring>
#include <cctype>
#include <cmath>
#include <stack>
#include <queue>
#include <vector>
#include <set>
#include <map>
#include <list>
#include <stdio.h>
#include <string.h>
#include <cstdlib>
#include <math.h>
#include <bitset>
#include <iterator>
#include <iomanip>
#include <sstream>
#include <numeric>
#define INF 2000000000
using namespace std;
int dx[4]={1,0,-1,0},dy[4]={0,1,0,-1};
long long gcd(long long a,long long b){if(a%b==0){return b;}else return gcd(b,a%b);}
long long lcm(long long a,long long b){if(a==0){return b;} return a/gcd(a,b)*b;}
long long MOD; template<class T> void mod(T &n){MOD=n;}
#define sym cout<<"---------"<<endl;
#define ll long long
#define PL pair<long long, long long>
#define P pair<int,int>
#define mk make_pair
#define en endl
#define WHITE 1
#define BLACK 2
#define GRAY 1
#define RE return 0
#define int ll

#define MAX 1005
int field[MAX][MAX];  // start -2  空き地 0 障害物 -1
P num[15];
int dist[MAX][MAX];

signed main(){
  int h,w,n;
  cin>>h>>w>>n;
  
  P start;
  for(int i=1; i<=h; i++){
    for(int j=1; j<=w; j++){
      char ch; cin>>ch;
      if(ch=='S') {start.first=j; start.second=i; field[i][j]=-2;}
      else if(ch=='.') field[i][j]=0;
      else if(ch=='X') field[i][j]=-1;
      else{ num[ch-'0'].first=j; num[ch-'0'].second=i; }
    }
  }
  
  int sum_time=0;
  for(int i=0; i<n; i++){
    int to=i+1;
    P now_where;
    if(!i){
      now_where.first=start.first;
      now_where.second=start.second;
    }else{
      now_where.first=num[i].first;
      now_where.second=num[i].second;
    }
    
    for(int i=0; i<=w; i++) for(int j=0; j<=h; j++) dist[i][j]=INF;
    dist[now_where.first][now_where.second]=0;
    
    int min_dist=INF;
    queue<P> que;
    que.push(mk(now_where.first,now_where.second));
    while(!que.empty()){
      int x=que.front().first; int y=que.front().second; que.pop();
      if(num[to].first==x&&num[to].second==y){
        min_dist=dist[x][y];
        break;
      }
      for(int k=0; k<4; k++){
        int xx=x+dx[k]; int yy=y+dy[k];
        if(xx<1||xx>w||yy<1||yy>h) continue;
        if(field[yy][xx]==-1) continue;
        if(dist[xx][yy]>dist[x][y]+1){
          dist[xx][yy]=dist[x][y]+1;
          que.push(mk(xx,yy));
        }
      }
    }
    
    sum_time+=min_dist;
  }
  
  cout<<sum_time<<en;
}

C++: #include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); i++)
#define shosu(n) setprecision(n)
#define INF 999999999
using namespace std;
int h, w, n;
string data[1100];
int main() {
  while (cin >> h >> w >> n) {
    rep(i, h) cin >> data[i];

    pair<int, int> ce[10];
    rep(i, h) rep(j, w) {
      if (data[i][j] == 'S') {
        ce[0] = pair<int, int>(i, j);
      }
      if (isdigit(data[i][j])) {
        ce[data[i][j] - '0'] = pair<int, int>(i, j);
      }
    }
    int sum = 0;
    rep(i, n) {
      int mp[1100][1100];
      rep(i, 1100) rep(j, 1100) mp[i][j] = INF;
      bool used[1100][1100] = {};

      mp[ce[i].first][ce[i].second] = 0;
      used[ce[i].first][ce[i].second] = true;
      queue<pair<int, int>> que;
      que.push(ce[i]);
      while (que.size()) {
        int y = que.front().first;
        int x = que.front().second;
        que.pop();
        int dx[] = {0, 1, 0, -1};
        int dy[] = {1, 0, -1, 0};
        rep(i, 4) {
          int ddy = y + dy[i];
          int ddx = x + dx[i];
          if (ddy >= 0 && ddy < h && ddx >= 0 && ddx < w &&
              data[ddy][ddx] != 'X' && !used[ddy][ddx]) {
            used[ddy][ddx] = true;
            mp[ddy][ddx] = mp[y][x] + 1;
            que.push(pair<int, int>(ddy, ddx));
          }
        }
      }
      sum += mp[ce[i + 1].first][ce[i + 1].second];
    }
    cout << sum << endl;
  }

  return 0;
}