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 <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <string>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <algorithm>

using namespace std;

#define rep(i,j) REP((i), 0, (j))
#define REP(i,j,k) for(int i=(j);(i)<(k);++i)
#define BW(a,x,b) ((a)<=(x)&&(x)<=(b))
#define ALL(v) (v).begin(), (v).end()
#define LENGTHOF(x) (sizeof(x) / sizeof(*(x)))
#define AFILL(a, b) fill((int*)a, (int*)(a + LENGTHOF(a)), b)
#define MP make_pair
#define PB push_back
#define F first
#define S second
#define Y first
#define X second
#define INF 1 << 30
#define EPS 1e-10

typedef pair<int, int> pi;
typedef pair<int, pi> pii;
typedef pair<pi, pi> pipi;
typedef vector<int> vi;
typedef queue<int> qi;
typedef long long ll;

int H, W, N;
char field[1024][1024];
int dy[] = {0,1,0,-1}, dx[] = {1,0,-1,0};

int main(){
  scanf("%d%d%d", &H, &W, &N);
  rep(i, H) scanf("%s", field[i]);

  int x, y;
  rep(i, H) rep(j, W) if(field[i][j] == 'S'){ y = i; x = j; break;}

  map<pi, int>m;
  m[MP(y, x)] = 1;
  queue<pipi>q;
  q.push(MP(MP(1, 0), MP(y, x)));
  while(!q.empty()){
    pipi p = q.front(); q.pop();
    if(field[p.S.Y][p.S.X] == p.F.F + '0'){
      if(p.F.F == N){
	printf("%d\n", p.F.S);
	break;
      }
      m.clear();
      while(!q.empty()) q.pop();
      m[MP(p.S.Y, p.S.X)] = 1;
      p.F.F++;
    }
    rep(d, 4){
      int ny = p.S.Y + dy[d], nx = p.S.X + dx[d];
      int hp = p.F.F, c = p.F.S;
      if(ny < 0 || ny >= H || nx < 0 || nx >= W || field[ny][nx] == 'X' || m.count(MP(ny, nx))) continue;
      m[MP(ny, nx)] = 1;
      q.push(MP(MP(hp, c+1), MP(ny, nx)));
    }
  }
  return 0;
}

C++: #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <queue>
#include <map>
#include <utility>
#include <functional>

using namespace std;

typedef pair<int, int> P;

int h, w, n;
char f[1000][1000];

int dx[] = { 0, 1, 0, -1 };
int dy[] = { -1, 0, 1, 0 };

struct Ele {
	Ele(int a, double b, P c) : g(a), h(b), p(c) {}
	bool operator<(const Ele& right) const {
		return g + h > right.g + right.h;
	}
	int g;
	double h;
	P p;
};

double euclidean(P s, P g) {
	int y = s.first - g.first;
	int x = s.second - g.second;
	return sqrt(x*x + y*y);
}

int Astar(P s, P g) {
	bool used[1000][1000] = { false };
	priority_queue<Ele> que;
	que.push(Ele(0, euclidean(s, g), s));

	while (!que.empty()) {
		Ele t = que.top();
		que.pop();

		if (t.p == g)
			return t.g;
		if (used[t.p.first][t.p.second])
			continue;
		used[t.p.first][t.p.second] = true;

		for (int i = 0; i < 4; ++i) {
			int ny = t.p.first + dy[i];
			int nx = t.p.second + dx[i];
			if (ny < 0 || ny >= h || nx < 0 || nx >= w || f[ny][nx] == 'X')
				continue;

			P np(ny, nx);
			que.push(Ele(t.g + 1, euclidean(np, g), np));
		}
	}

	return 0;
}

int main() {
	cin >> h >> w >> n;

	P fac[10];
	for (int i = 0; i < h; ++i) {
		for (int j = 0; j < w; ++j) {
			cin >> f[i][j];
			if ('1' <= f[i][j] && f[i][j] <= '9')
				fac[f[i][j] - '0'] = P(i, j);
			else if (f[i][j] == 'S')
				fac[0] = P(i, j);
		}
	}

	int ans = 0;
	for (int i = 0; i < n; ++i) {
		ans += Astar(fac[i], fac[i + 1]);
	}

	cout << ans << endl;

	return 0;
}

C++: #include <iostream>
#include <queue>
using namespace std;
#define MAXN 1001
char A[MAXN][MAXN];
int w,h,n;
int s[2];

void input()
{
    cin>>h>>w>>n;
    for(int i=0;i<h;i++){
        for(int j=0;j<w;j++){
            cin>>A[i][j];
            if(A[i][j]=='S'){
                s[0]=i;
                s[1]=j;
            }
        }
    }
}

int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};
typedef pair<pair<int,int>,int> P;

int known[MAXN][MAXN];

int bfs(int& x, int& y, char k)
{
    queue<P>que;
    que.push(P(make_pair(x, y), 0));
    while(!que.empty()){
        P cur = que.front();
        // cout<<"*"<<cur.first.first<<" "<<cur.first.second<<endl;
        que.pop();
        if(A[cur.first.first][cur.first.second]==k){
            x = cur.first.first;
            y = cur.first.second;
            return cur.second;
        }
        for(int i=0;i<4;i++){
            int nx = cur.first.first+dx[i];
            int ny = cur.first.second+dy[i];
            if(0<=nx&&nx<h && 0<=ny&&ny<w && A[nx][ny]!='X' && !known[nx][ny]){
                que.push(P(make_pair(nx, ny), cur.second+1));
                known[nx][ny]=1;
            }
        }
    }
    return 0x3fffffff;
}

int main()
{
    input();
    int res = 0;
    int x, y;
    x = s[0];
    y = s[1];

    for(int i=1;i<=n;i++){
        memset(known, 0, sizeof(int)*MAXN*MAXN);
        int tmp = bfs(x, y, '0'+i);
        res += tmp;
    }
    cout<<res<<endl;
    return 0;
}

C++: #include<stdio.h>
#include<string.h>
#include<queue>
#include<algorithm>
#define MAX_N 1002
using namespace std;
struct node{int x,y;};
char _map[MAX_N][MAX_N];
int dp[MAX_N][MAX_N];
int ox[]={0,0,1,-1};
int oy[]={1,-1,0,0};
int S_x,S_y;
int h,w,cnt;

node make_node(int x,int y){
    node t;
    t.x=x,t.y=y;
    return t;
}
void solve(){
    queue<node> que;
    int step=0;

    for(int i=1;i<=cnt;i++){
        que.push(make_node(S_x,S_y));
        _map[S_x][S_y]='.';
        memset(dp,-1,sizeof(dp));
        dp[S_x][S_y]=step;
        while(!que.empty()){
            node t=que.front();que.pop();
            if(_map[t.x][t.y]=='0'+i){
                step=dp[t.x][t.y];
                S_x=t.x,S_y=t.y;
                break;
            }
            for(int j=0;j<4;j++){
                int x=t.x+ox[j];
                int y=t.y+oy[j];
                if(0<=x&&x<h&&0<=y&&y<w&&_map[x][y]!='X'&&dp[x][y]==-1){
                    que.push(make_node(x,y));
                    dp[x][y]=dp[t.x][t.y]+1;
                }
            }
        }
        while(!que.empty()) que.pop();
    }

    printf("%d\n",step);
}

int main()
{
    while(scanf("%d%d%d",&h,&w,&cnt)!=EOF){
        for(int i=0;i<h;i++)
            scanf("%s",_map[i]);
        for(int j=0;j<h;j++)
            for(int k=0;k<w;k++)
                if(_map[j][k]=='S')
                    S_x=j,S_y=k,j=h,k=w;
        solve();
    }
    return 0;
}