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 <algorithm>
#include <bitset>
#include <cassert>
#include <cmath>
#include <ctime>
#include <functional>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>

#define REP(i,n)   for (int i = 0; i < (n); ++i)
#define SORT(a)    sort((a).begin(), (a).end());
#define UNIQ(a)    SORT(a);(a).erase(unique((a).begin(), (a).end()), (a).end());
#define FIND(a,x)  find((a).begin(), (a).end(), (x)) != (a).end()
#define REVERSE(a) reverse((a).begin(), (a).end());

using namespace std;
using ll = long long;
using P = pair<int,int>;

const int MOD = 1000000007; // 10^9 + 7
const int INF = 1000000000;
const int dx[4] = {0, 0, -1, 1};
const int dy[4] = {-1, 1, 0, 0};

int H, W, N;
int mins[1000][1000];

int getMinPath(string m[], int sy, int sx, int gy, int gx) {
  queue<tuple<int, int, int>> q; q.push(make_tuple(sy, sx, 0));

  mins[sy][sx] = 0;

  while (!q.empty()) {
    tuple<int, int, int> t = q.front(); q.pop();
    int y = get<0>(t);
    int x = get<1>(t);
    int c = get<2>(t);

    // cout << "y = " << y << ", x = " << x << ", c = " << c << endl;

    if (y == gy && x == gx) return c;

    mins[y][x] = c;

    REP(i, 4) {
      int nx = x + dx[i];
      int ny = y + dy[i];

      if (0 <= nx && nx < W && 0 <= ny && ny < H && m[ny][nx] != 'X' && c + 1 < mins[ny][nx]) {
        q.push(make_tuple(ny, nx, c + 1));
        mins[ny][nx] = c + 1;
      }
    }
  }

  assert(false);
  return -1;
}

int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);

  cin >> H >> W >> N;
  string m[H]; REP(i, H) cin >> m[i];
  vector<P> v(N + 1);
  int ans = 0;

  REP(i, H)REP(j, W) {
    int n = m[i][j] - '0';
    P p = make_pair(i, j);

    if (1 <= n && n <= N)
      v[n] = p;
    else if (m[i][j] == 'S')
      v[0] = p;
  }

  // for (int i = 0; i < v.size(); i++) {
  //   cout << "(" << v[i].first << "," << v[i].second << ")" << endl;
  // }

  for (int i = 1; i <= N; i++) {
    REP(i, H)REP(j, W) mins[i][j] = INF;

    ans += getMinPath(m, v[i - 1].first, v[i - 1].second, v[i].first, v[i].second);
  }

  cout << ans << endl;
}

C++: #include<map>
#include<queue>
#include<stdio.h>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define SIZE 1010
using namespace std;

typedef pair<int,int> P;

char mass[SIZE][SIZE];
int  data[SIZE][SIZE];
int  dx[4]={1,0,-1,0};
int  dy[4]={0,1,0,-1};
int  sx,sy,gx,gy;
int  h,w,n;
int  k;
int  sum=0;

int bfs();

int main(){

  int i,j;

  cin>>h>>w>>n;

  for(i=0;i<h;i++){
    for(j=0;j<w;j++){
      cin>>mass[i][j];
    }
  }

  for(i=0;i<h;i++){
    for(j=0;j<w;j++){
      if(mass[i][j]=='S'){
	sx=j;
	sy=i;
	break;
      }
    }
  }

  for(k=1;k<=n;k++){
    for(i=0;i<h;i++){
      for(j=0;j<w;j++){
	if(mass[i][j]-'0'==k){
	  gx=j;
	  gy=i;
	}
      }
    }
    sum+=bfs();
    sx=gx;
    sy=gy;
  }                      
  
  cout<<sum<<endl;
  
  return 0;
}
int bfs(){

  int i,j,now=0;
  queue<P> que;

  memset(data,-1,sizeof(data));

  que.push(P(sy,sx));
  data[sy][sx]=0;

  while(!que.empty()){

    P p=que.front();
    que.pop();

    if(p.first==gy && p.second==gx){
      return data[p.first][p.second];
    }

    for(i=0;i<4;i++){
      int nx=p.second+dx[i];
      int ny=p.first+dy[i];

      if(nx>=0 && nx<=w && ny>=0 && ny<=h && mass[ny][nx]!='X' && data[ny][nx]==-1){
	que.push(P(ny,nx));
	data[ny][nx]=data[p.first][p.second]+1;
    }
   }
  }
 return 0;
}

C++: #include<iostream>
#include<vector>
#include<map>
#include<utility>
#include<queue>
using namespace std;
 
char f[1001][1001];
int d[1001][1001];
int h , w , n , x , y , ans;
typedef pair<int,int> P;
int dx[] = {1,0,-1,0} , dy[] = {0,-1,0,1};
 
int bfs(int to){
  for( int i = 0 ; i < h ; i++)
    for( int j = 0 ; j < w ; j++)
      d[i][j] = 0;
  queue<P> q;
  q.push(make_pair(x,y));
  d[x][y]=1;
  while(!q.empty()){
    P p = q.front();
    q.pop();
    if(f[p.second][p.first] - '0' == to){
      x = p.first;
      y = p.second;
      break;
    }
    for(int i = 0 ; i < 4 ; i ++){
      int nx = p.first + dx[i], ny = p.second + dy[i];
      if(nx >= 0 && nx < w && ny < h && ny >=0 && d[ny][nx] == 0 && f[ny][nx] != 'X'){
        d[ny][nx] = d[p.second][p.first] + 1;
        q.push(make_pair(nx,ny));
        
      }
    }
  }
  return d[y][x] - 1;
} 
 
int main(){
  cin >> h >> w >> n;
  for( int i = 0 ; i < h ; i++) cin >> f[i];
  for( int i = 0 ; i < h ; i++){ 
    for( int j = 0 ; i < w ; i++){
      if(f[j][i]=='S'){
        x = j;
        y = i;
      }
    }
  }
  for( int i = 0 ; i < n ; i++ ) ans +=bfs(i) ; 
  cout << ans << endl;
}

C++: #include <iostream>
#include <queue>
#include <map>

using namespace std;

typedef pair<int, int> pii;

// ?????°
constexpr int MAX_SCALE = 1010;
constexpr int INF = 1000;

// input
int height, width, max_search_num;
int sx, sy;
int gx, gy;
char maze[MAX_SCALE][MAX_SCALE];

// ???????????§??????????????¢?????????
int d[MAX_SCALE][MAX_SCALE];

int ans = 0;

int bfs(pii relay_pos, int num)
{
    // init
    for (int y = 0; y < height; ++y) {
        for (int x = 0; x < width; ++x) {
            d[y][x] = INF;
            if (maze[y][x] == num + '0') {
                gx = x; gy = y;
            }
        }
    }

    // ??????????¨??????????
    queue<pii> que;
    que.push(relay_pos);
    int dx[4] = {1, 0, 0, -1};
    int dy[4] = {0, -1, 1, 0};

    // start??°???
    d[relay_pos.second][relay_pos.first] = 0;

    while (!que.empty()) {
        pii p = que.front(); que.pop();

        if (p.first == gx && p.second == gy) {
            break;
        }

        for (int i = 0; i < 4; ++i) {
            int nx = p.first + dx[i], ny = p.second + dy[i];

            if (nx >= 0 && nx < width && ny >= 0 && ny < height && maze[ny][nx] != 'X' && d[ny][nx] == INF) {
                que.push(pii(nx, ny));
                d[ny][nx] = d[p.second][p.first] + 1;
            }
        }
    }

    ans += d[gy][gx];

    if (num != max_search_num) bfs(pii(gx, gy), num + 1);

    return ans;
}

void solve()
{
    int res = bfs(pii(sx, sy), 1);

    cout << res << endl;
}

int main()
{
    cin >> height >> width >> max_search_num;

    for (int y = 0; y < height; ++y) {
        for (int x = 0; x < width; ++x) {
            cin >> maze[y][x];
            if (maze[y][x] == 'S') {
                sx = x; sy = y;
            }
        }
    }

    solve();
    
    return 0;
}