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 <utility>
#include <limits>
using namespace std;
typedef pair<int, int> P;
const int MAX_H = 1000, MAX_W = 1000, MAX_N = 9;
int h, w, n;
char c[MAX_H][MAX_W];
int sx, sy;
int d[MAX_H][MAX_W];
const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};
const int INF = numeric_limits<int>::max();
int gx[MAX_N], gy[MAX_N];

int bfs()
{
	queue<P> que;
	
	for(int i = 0; i != h; ++i){
		for(int j = 0; j != w; ++j){
			d[i][j] = INF;
		}
	}
	
	que.push(P(sx, sy));
	d[sx][sy] = 0;
	
	int count = 0;
	while(!que.empty()){		
		P p=que.front();
		que.pop();
		
		if(p.first == gx[count] && p.second == gy[count]){
			count++;
			
			while(!que.empty())
				que.pop();
			
			int score = d[p.first][p.second];
			for(int i = 0; i != h; ++i){
				for(int j = 0; j != w; ++j){
					d[i][j] = INF;
				}
			}
			d[p.first][p.second] = score;
		}
			
		if(count == n)
			break;
		
		for(int i = 0; i != 4; ++i){
			int nx = p.first + dx[i],
				ny = p.second + dy[i];
			
			if(0 <= nx && nx < h && 0 <= ny && ny < w &&
				c[nx][ny] != 'X' && d[nx][ny] == INF){
				que.push(P(nx, ny));
				d[nx][ny] = d[p.first][p.second] + 1;
			}
		}
		
	}
	
	return d[gx[n - 1]][gy[n - 1]];
	
}
int main()
{
	cin.tie(0);
	ios::sync_with_stdio(false);
	
	cin >> h >> w >> n;
	for(int i = 0; i != h; ++i){
		for(int j = 0; j != w; ++j){
			char a;
			cin >> a;
			if(a == 'S')
				sx = i, sy = j;
			if('1' <= a && a <= '9')
				gx[a - '0' - 1] = i, gy[a - '0' - 1] = j;
			c[i][j] = a;
		}
	}
	
	cout << bfs() << endl;
	
	return 0;
}

C++: #include <bits/stdc++.h>

using namespace std;

#define all(c) ((c).begin()), ((c).end())
#define dump(c) cerr << "> " << #c << " = " << (c) << endl;
#define iter(c) __typeof((c).begin())
#define tr(i, c) for (iter(c) i = (c).begin(); i != (c).end(); i++)
#define REP(i, a, b) for (int i = a; i < (int)(b); i++)
#define rep(i, n) REP(i, 0, n)
#define mp make_pair
#define fst first
#define snd second
#define pb push_back

typedef unsigned int uint;
typedef long long ll;
typedef unsigned long long ull;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<double> vd;
typedef vector<vd> vvd;
typedef vector<string> vs;
typedef pair<int, int> pii;

const int INF = 1 << 29;
const double EPS = 1e-10;

double zero(double d) {
    return d < EPS ? 0.0 : d;
}

template<typename T1, typename T2>
ostream &operator<<(ostream &os, const pair<T1, T2> &p) {
    return os << '(' << p.first << ',' << p.second << ')';
}

template<typename T>
ostream &operator<<(ostream &os, const vector<T> &a) {
    os << '[';
    rep(i, a.size()) os << (i ? " " : "") << a[i];
    return os << ']';
}

// to avoid error on mingw
string toString(int i) {
    stringstream ss;
    ss << i;
    return ss.str();
}

const int M = 1000000007;
// a^k
ll fpow(ll a, ll k, int M) {
    ll res = 1ll;
    ll x = a;
    while (k != 0) {
        if ((k & 1) == 1)
            res = (res * x) % M;
        x = (x * x) % M;
        k >>= 1;
    }
    return res;
}

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

int main() {
    cout.setf(ios::fixed, ios::floatfield);
    cout.precision(8);
    ios_base::sync_with_stdio(false);

    int H,W,N;
    cin >> H >> W >> N;

    int a[H][W];
    memset(a, 0, sizeof(a));
    bool vis[H][W];
    memset(vis, 0, sizeof(vis));

    int start = 0;
    rep(r,H) {
        string t;
        cin >> t;
        rep(c,W) {
            if(t[c] == 'S')
                start = r*W + c;
            else if(t[c] == 'X')
                a[r][c] = -1;
            else if(t[c] != '.')
                a[r][c] = t[c] - '0';
        }
    }

    queue<pii> que;
    que.push(mp(start,0));

    int target = 1;
    int ans = 0;
    while(!que.empty()) {
        pii t = que.front(); que.pop();
        int r = t.first / W;
        int c = t.first % W;
        int dist = t.second;

        vis[r][c] = true;

        //cerr << r << " " << c << " " << dist << " " << ans << endl;

        if(a[r][c] == target) {
            ans += dist;

            if(target == N)
                break;
            target++;

            que = queue<pii>();
            start = r * W + c;
            que.push(mp(start,0));

            memset(vis, 0, sizeof(vis));
            vis[r][c] = true;
            continue;
        }

        rep(i,4) {
            int nr = r + dy[i];
            int nc = c + dx[i];

            if(nr < 0 || H <= nr || nc < 0 || W <= nc || a[nr][nc] == -1)
                continue;

            if(!vis[nr][nc])
                que.push(mp(nr*W+nc, dist+1));
        }
    }

    cout << ans << endl;

    return 0;
}

C++: //??????????¨????????????????????¬¬??????????¢?
//BFS
#include <iostream>
#include <queue>
#include <stdio.h>
#include <string.h>
#include <limits.h>
#define MAX_H 1001
#define MAX_W 1001
#define MAX_N 10

using namespace std;

typedef pair<int,int> P;
int H,W,N;
int sx,sy;
int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};
char Loc[MAX_H][MAX_W];
int FoodX[MAX_N];
int FoodY[MAX_N];

int BFS(int sa,int sb,int ea,int eb)
{
    int D[H][W];
    for(int i=0;i<H;i++)
        for(int j=0;j<W;j++) D[i][j]=INT_MAX;
    queue<P> que;
    que.push(P(sa,sb));
    D[sa][sb]=0;
    while(que.size())
    {
        P p=que.front();
        for(int i=0;i<4;i++)
        {
            int nx=p.first+dx[i],ny=p.second+dy[i];
            if(nx>=0&&nx<H&&ny>=0&&ny<W&&Loc[nx][ny]!='X'&&D[nx][ny]==INT_MAX)
            {
                que.push(P(nx,ny));
                D[nx][ny]=D[p.first][p.second]+1;
            }
            if(nx==ea&&ny==eb) return D[nx][ny];
        }
        que.pop();
    }
}

int main()
{
    cin>>H>>W>>N;
    int k=0,step=0;
    for(int i=0;i<H;i++)
    {
        getchar();
        for(int j=0;j<W;j++)
        {
            scanf("%c",&Loc[i][j]);
            if(Loc[i][j]=='S') {sx=i;sy=j;}
            if(Loc[i][j]>='1'&&Loc[i][j]<='9') {FoodX[Loc[i][j]-'0']=i;FoodY[Loc[i][j]-'0']=j;}
        }
    }
    FoodX[0]=sx;
    FoodY[0]=sy;
    for(int i=0;i<N;i++)
    {
        step+=BFS(FoodX[i],FoodY[i],FoodX[i+1],FoodY[i+1]);
    }
    cout<<step<<endl;
    return 0;
}