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 <cassert>
#include <cctype>
#include <cmath>
#include <climits>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>

#include <algorithm>
#include <bitset>
#include <deque>
#include <functional>
#include <iterator>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <utility>
#include <vector>

#include <fstream>
#include <iostream>
#include <sstream>

#include <iomanip>

using namespace std;

typedef pair<int, int> pint;
typedef vector<int> vint;
typedef long long ll;

#define ALL(c) (c).begin(),(c).end()
#define RALL(c) (c).rbegin(),(c).rend()
#define SORT(c) sort(ALL(c))

#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n)  for(int i=0;i<(n);++i)

#define NEXTP(c) next_permutation(ALL(c))
#define SUM(c) accumulate(ALL(c),0)
#define MP( a, b ) make_pair( ( a ), ( b ) )

#define ANS(x)  cout << (x) << endl;
#define DUMP(x)  cerr << #x << " = " << (x) << endl;

#define INF 1000000000 // 10^9
const double EPS = 1e-10;

//Template End
class dat{
public:
    int x;
    int y;
    int t;
};

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

int main(){
    int H,W,N;
    cin>>H>>W>>N;
    vector<string> board(H);
    REP(i, H)cin>>board[i];
    
    int time = 0;
    
    dat start;
    
    REP(i, H){
        REP(j, W){
            if(board[i][j]=='S'){
                start.x=i;
                start.y=j;
                start.t=0;
            }
        }
    }
    
    REP(i,N){
        queue<dat> que;
        que.push(start);
        
        bool visited[1000][1000]={};
        visited[start.x][start.y]=true;
        
        while (que.size()) {
            dat now = que.front();
            que.pop();
            if (board[now.x][now.y]=='1'+i) {
                
                time+=now.t;
                start = now;
                start.t=0;
                break;
            }
            
            REP(j, 4){
                int nx = now.x+dx[j];
                int ny = now.y+dy[j];
                
                if (0<=nx&&nx<H&&
                    0<=ny&&ny<W&&
                    board[nx][ny]!='X'&&
                    !visited[nx][ny]) {
                    visited[nx][ny]=true;
                    dat next;
                    next.x=nx;
                    next.y=ny;
                    next.t=now.t+1;
                    que.push(next);
                }
            }
            
        }
    }
    cout<<time<<endl;
    return 0;
}

C++: #include <iostream>
#include <cstdio>
#include <queue>
using namespace std;

struct Node{
	int x,y;
};

const int max_n=1000+10;
int h,w,n,sx,sy,dx[]={0,0,-1,1},dy[]={-1,1,0,0},d[max_n][max_n],ans;
Node sN;
char c[max_n][max_n];

void bfs(int m){
	if(m>n)return;
	queue<Node> q;
	memset(d,0,sizeof(d));
	q.push(sN);
	d[sN.x][sN.y]=1;
	while(!q.empty()){
		Node p=q.front();
		q.pop();
		if(c[p.x][p.y]=='0'+m){
		    ans+=d[p.x][p.y]-1;
		    sN.x=p.x;
		    sN.y=p.y;
		    bfs(m+1);
		    return;
		}
		for(int i=0;i<4;i++){
			Node nN;
			nN.x=p.x+dx[i];
			nN.y=p.y+dy[i];
			if(nN.x>=0 && nN.y<h 
            && nN.y>=0 && nN.y<w 
		   	&& c[nN.x][nN.y]!='X' && !d[nN.x][nN.y]){
				q.push(nN);
				d[nN.x][nN.y]=d[p.x][p.y]+1;
			}
		}
	}
}

int main(){
    scanf("%d%d%d",&h,&w,&n);
    for(int i=0;i<h;i++)
        for(int j=0;j<w;j++){
            cin>>c[i][j];
            if(c[i][j]=='S'){sN.x=i;sN.y=j;}
        }
    bfs(1);
    cout<<ans<<endl;
    return 0;
}

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

using namespace std;

int h, w, n;

char map[1001][1001];

int vis[1001][1001];

const int v[2][4] = { {1,0,-1,0},{0,-1,0,1} };

queue<pair<int ,int>> Pos;
queue <pair<int, pair< int, int > > > que;


int main() {
	cin >> h >> w >> n;
	for (int i = 1; i <= h; i++) {
		for (int j = 1; j <= w; j++) {
			cin >> map[i][j];
			if (map[i][j] == 'S')que.push(make_pair(0,make_pair(i,j)));
		}
	}
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= h; j++) {
			for (int k = 1; k <= w; k++) {
				if (map[j][k] - '0' == i)Pos.push(make_pair(j,k));
			}
		}
	}
	int ct = 0;
	while (Pos.size()) {
		pair<int, int > P = Pos.front();
		Pos.pop();
		while (que.size()) {
			pair<int,pair< int,int > > a = que.front();
			que.pop();
			if (vis[a.second.first][a.second.second] != 0)continue;
			vis[a.second.first][a.second.second] = a.first + 1;
			if (a.second.first == P.first&&a.second.second == P.second) {
				ct += vis[a.second.first][a.second.second];
				for (int i = 1; i <= h; i++) {
					for (int j = 1; j <= w; j++) {
						vis[i][j] = 0;
					}
				}
				while (que.size())que.pop();
				if(Pos.size())que.push(make_pair(0,make_pair(a.second.first,a.second.second)));
				ct -= 1;
				break;
			}
			for (int i = 0; i < 4; i++) {
				int px= a.second.first + v[0][i], py= a.second.second + v[1][i];
				if (1 <= px&&px <= h && 1 <= py&&py <= w&&vis[px][py] == 0 && map[px][py] != 'S'&&map[px][py]!='X') {
					que.push(make_pair(vis[a.second.first][a.second.second], make_pair(px, py)));
				}
			}
		}
	}
	cout << ct << endl;
	return 0;
}

C++: //Aizu 0558
//DinnerHunt
#include <cstdio>
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
const int maxd = 1005;
typedef pair<int,int> P;
char arr[maxd][maxd];
int flag[maxd][maxd];
int n,m,k,qx,qy,ans;
int fx[] = {1,-1,0,0 }, fy[] = { 0,0,1,-1 }; 
void bfs(){
	ans = 1;
	queue<P> que;
	que.push(P(qx,qy));
	flag[qx][qy] = 1;
	while(!que.empty())
	{
		P p = que.front();que.pop();
		for(int i=0;i<4;i++){
			int x = p.first+fx[i] , y = p.second+fy[i], z = flag[p.first][p.second];
			if(x>=0&&x<n&&y>=0&&y<m&&arr[x][y]!='X'&&!flag[x][y])
			{
				if(arr[x][y] =='0'+ans)
				{   
					if(ans==k){printf("%d",z);return;}
                    memset(flag,0,sizeof(flag));
					while(!que.empty()) que.pop();
                    ans++;
                    flag[x][y] = z+1;
				    que.push(P(x,y));
                    break;
				}
				flag[x][y] = z+1;
				que.push(P(x,y));
			}
		}
	}
}
int main(){
	while(scanf("%d %d %d",&n,&m,&k)==3&&n&&m)
	{
		arr[0][0] = getchar();
		for(int i=0;i<n;i++)
			for(int j=0;j<=m;j++)
			{
				arr[i][j] = getchar();
				if(arr[i][j] == 'S') qx=i,qy=j;
			}
		bfs();
	}
	return 0;
}