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<map>
#include<vector>
#include<stdlib.h>
using namespace std;
typedef pair<int,int> P;
main(){
  int h,w,n,count=0;
  P zahyou[10];
  queue<P> haba,syokika;
  char maps[1001][1001];
  int min_cost[1001][1001];
  P start,now;
  P kiokua;
  int dx[4]={0,1,0,-1};
  int dy[4]={1,0,-1,0};
  cin>>h>>w>>n;
  for(int i=0;i<h;i++){
    for(int j=0;j<w;j++){
      cin>>maps[i][j];
      min_cost[i][j]=-1;
      if(maps[i][j]=='S'){
	start.first=i;
	start.second=j;
	min_cost[i][j]=0;
      }
      else if(maps[i][j]!='.'&&maps[i][j]!='X'&&maps[i][j]!='S'){
	int a;
	for(int k=1;k<=9;k++){
	  if(maps[i][j]=='0'+k){
	    a=k;
	    break;
	  }
	}
	zahyou[a].first=i;
	zahyou[a].second=j;
      }
    }
  }
  haba.push(start);
  syokika.push(start);
  for(int i=1;i<=n;i++){
    while(!haba.empty()){
      if(haba.front().first==zahyou[i].first&&haba.front().second==zahyou[i].second){
	count=count+min_cost[haba.front().first][haba.front().second];
	while(!syokika.empty()){
	  min_cost[syokika.front().first][syokika.front().second]=-1;
	  syokika.pop();
	}
	min_cost[haba.front().first][haba.front().second]=0;
	kiokua=haba.front();
	while(!haba.empty()){
	  haba.pop();
	}
      }
      else{
	for(int j=0;j<4;j++){
	  int nx,ny;
	  nx=haba.front().first+dx[j];
	  ny=haba.front().second+dy[j];
	  if(nx>=0&&h>nx&&ny>=0&&w>ny&&min_cost[nx][ny]==-1&&maps[nx][ny]!='X'){
	    min_cost[nx][ny]=min_cost[haba.front().first][haba.front().second]+1;
	    P a;
	    a.first=nx;
	    a.second=ny;
	    haba.push(a);
	    syokika.push(a);
	  }
	}
	haba.pop();
      }
    }
    haba.push(kiokua);
    syokika.push(kiokua);
  }
  cout<<count<<endl;
}

C++: #include<iostream>
#include<queue>
using namespace std;
typedef pair<int, int> P;
char G[1005][1005];
int vis[1005][1005];
int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};
int h, w, n;
int main()
{
    for(int i = 0; i < 1005; i++)
        for(int j = 0; j < 1005; j++)
            G[i][j] = 'X';
    int sx, sy;
    cin >> h >> w >> n;
    for(int i = 1; i <= h; i++)
        for(int j = 1; j <= w; j++)
        {
            cin >> G[i][j];
            if(G[i][j] == 'S') {sx = i; sy = j;}
        }
    int ans = 0;
    for(int i = 1; i <= n; i++)
    {
        for(int j = 1; j <= h; j++)
            for(int k = 1; k <= w; k++)
                vis[j][k] = 0;
        queue<pair<P, int> > que;
        que.push(pair<P, int>(P(sx, sy), 0));
        vis[sx][sy] = 1;
        while(!que.empty())
        {
            P node = que.front().first; int steps = que.front().second; que.pop();
            int x = node.first, y = node.second;
            if(G[x][y] == i + '0')
            {
                sx = x;
                sy = y;
                ans += steps;
                break;
            }
            for(int j = 0; j < 4; j++)
                if(!vis[x + dx[j]][y + dy[j]] && G[x + dx[j]][y + dy[j]] != 'X')
                {
                    que.push(pair<P, int>(P(x + dx[j], y + dy[j]), steps + 1));
                    vis[x + dx[j]][y + dy[j]] = 1;
                }
        }
    }
    printf("%d\n", ans);
    return 0;
}

C++: #include<iostream>
#include<queue>
#include<utility>
int H, W, N;
int sh, sw;
char tar[9] = { '1','2','3','4','5','6','7','8','9' };
char HW[1000][1000];
int cnt = 0;
const int INF = 1 << 30;
int ans;
int tx, ty;
int D[1000][1000];
void solve(int h, int w) {
	std::queue<std::pair<int, int>> q;
	q.push(std::make_pair(h, w));
	for (int a = 0; a < H; a++) {
		for (int b = 0; b < W; b++) {
			D[a][b] = INF;
		}
	}
	D[h][w] = 0;
	while (q.size()) {
		std::pair<int, int> p = q.front();
		q.pop();
		if (HW[p.first][p.second] == tar[cnt]) {
			ans += D[p.first][p.second];
			tx = p.first;
			ty = p.second;
			return;
		}
		int dx[4] = { 0,1,0,-1 }, dy[4] = { 1,0,-1,0 };
		for (int i = 0; i < 4; i++) {
			int ux = p.first + dx[i];
			int uy = p.second + dy[i];
			if (0 <= ux&&ux < H && 0 <= uy&&uy < W&&D[ux][uy] == INF&&HW[ux][uy] != 'X') {
				q.push(std::make_pair(ux, uy));
				D[ux][uy] = D[p.first][p.second] + 1;
			}
		}
	}
	return;
}
int main() {
	std::cin >> H >> W >> N;
	for (int i = 0; i < H; i++) {
		for (int j = 0; j < W; j++) {
			std::cin >> HW[i][j];
			if (HW[i][j] == 'S') {
				sh = i;
				sw = j;
			}
		}
	}
	solve(sh, sw);
	for (int i = 0; i < N; i++) {
		cnt = i;
		solve(tx, ty);
	}
	std::cout << ans << "\n";
	return 0;
}

C++: 

#include<iostream>
#include<queue>
#include<utility>
using namespace std;
typedef long long ll;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)


const int MAX = 1001;
char area[MAX][MAX];
char bak[MAX][MAX];
int dst[MAX][MAX];
int mx, my;
vector<pair<int, int>> kouho;


int adj(int x, int m) {

	if (x < 0) return 0;
	if (x >= m) return m - 1;

	return x;
}

int ctoi(char c) {
	if (c >= '0' && c <= '9') {
		return c - '0';
	}
	return 0;
}

int main() {



	int n, m, pw, fc, sx, sy, stp, nxt;
	queue < pair<int, int>> q;
	pw = nxt = 1;
	stp = 0;
	cin >> my >> mx >> fc;


	rep(i, my) {
		cin >> area[i];

		rep(j, mx) {
			dst[i][j] = -1;

			if (area[i][j] == 'S') {
				sx = j;
				sy = i;
			}
		}
	}


	int dx[] = { 1,0,-1,0 };
	int dy[] = { 0,1,0,-1 };
	q.push(make_pair(sx, sy));
	dst[sy][sx] = 0;

	while (!q.empty())
	{
		auto pr = q.front();q.pop();
		int x, y, nx, ny;
		x = pr.first;
		y = pr.second;

		rep(i, 4) {

			nx = adj(x + dx[i], mx);
			ny = adj(y + dy[i], my);

			if (area[ny][nx] == 'X') continue;

			if (dst[ny][nx] == -1) {
				if (ctoi(area[ny][nx]) == nxt) {
					stp += dst[y][x] + 1;
					nxt += 1;

					rep(i, my) {
						rep(j, mx) {
							dst[i][j] = -1;
						}
					}
					dst[ny][nx] = 0;
					queue < pair<int, int>> dd;
					q = dd;
					q.push(make_pair(nx, ny));
					break;
				}
				else
				{
					dst[ny][nx] = dst[y][x] + 1;
					q.push(make_pair(nx, ny));
				}
			}
		}
	}

	cout << stp << endl;
}