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++: #define _CRT_SECURE_NO_WARNINGS
#include "bits/stdc++.h"
#include <random>

using namespace std;

//呪文
#define DUMPOUT cerr
#define dump(...) DUMPOUT<<"  ";DUMPOUT<<#__VA_ARGS__<<" :["<<__LINE__<<":"<<__FUNCTION__<<"]"<<endl;DUMPOUT<<"    ";dump_func(__VA_ARGS__)

typedef unsigned uint; typedef long long ll; typedef unsigned long long ull; typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef pair<double, double> pdd; typedef pair<string, string> pss;
template <typename _KTy, typename _Ty> ostream& operator << (ostream& ostr, const pair<_KTy, _Ty>& m) { ostr << "{" << m.first << ", " << m.second << "}"; return ostr; }
template <typename _KTy, typename _Ty> ostream& operator << (ostream& ostr, const map<_KTy, _Ty>& m) { if (m.empty()) { ostr << "{ }"; return ostr; } ostr << "{" << *m.begin(); for (auto itr = ++m.begin(); itr != m.end(); itr++) { ostr << ", " << *itr; } ostr << "}"; return ostr; }
template <typename _Ty> ostream& operator << (ostream& ostr, const vector<_Ty>& v) { if (v.empty()) { ostr << "{ }"; return ostr; } ostr << "{" << v.front(); for (auto itr = ++v.begin(); itr != v.end(); itr++) { ostr << ", " << *itr; }	ostr << "}"; return ostr; }
template <typename _Ty> ostream& operator << (ostream& ostr, const set<_Ty>& s) { if (s.empty()) { ostr << "{ }"; return ostr; } ostr << "{" << *(s.begin()); for (auto itr = ++s.begin(); itr != s.end(); itr++) { ostr << ", " << *itr; }	ostr << "}"; return ostr; }
template <typename _Ty> ostream& operator << (ostream& ostr, const stack<_Ty>& s) { if (s.empty()) { ostr << "{ }"; return ostr; } stack<_Ty> t(s); ostr << "{" << t.top(); t.pop(); while (!t.empty()) { ostr << ", " << t.top(); t.pop(); } ostr << "}";	return ostr; }
template <typename _Ty> ostream& operator << (ostream& ostr, const list<_Ty>& l) { if (l.empty()) { ostr << "{ }"; return ostr; } ostr << "{" << l.front(); for (auto itr = ++l.begin(); itr != l.end(); ++itr) { ostr << ", " << *itr; } ostr << "}"; return ostr; }
template <typename _KTy, typename _Ty> istream& operator >> (istream& istr, pair<_KTy, _Ty>& m) { istr >> m.first >> m.second; return istr; }
template <typename _Ty> istream& operator >> (istream& istr, vector<_Ty>& v) { for (size_t i = 0; i < v.size(); i++) istr >> v[i]; return istr; }
namespace aux { // print tuple
	template<typename Ty, unsigned N, unsigned L> struct tp { static void print(ostream& os, const Ty& v) { os << get<N>(v) << ", "; tp<Ty, N + 1, L>::print(os, v); } };
	template<typename Ty, unsigned N> struct tp<Ty, N, N> { static void print(ostream& os, const Ty& value) { os << get<N>(value); } };
}
template<typename... Tys> ostream& operator<<(ostream& os, const tuple<Tys...>& t) { os << "{"; aux::tp<tuple<Tys...>, 0, sizeof...(Tys)-1>::print(os, t); os << "}"; return os; }

template<typename A, size_t N, typename T> inline void Fill(A(&array)[N], const T &val) { std::fill((T*)array, (T*)(array + N), val); }

void dump_func() { DUMPOUT << endl; }
template <class Head, class... Tail> void dump_func(Head&& head, Tail&&... tail) { DUMPOUT << head; if (sizeof...(Tail) == 0) { DUMPOUT << " "; } else { DUMPOUT << ", "; } dump_func(std::move(tail)...); }

#define PI 3.14159265358979323846
#define EPS 1e-11
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n)  FOR(i,0,n)
#define all(x) (x).begin(), (x).end()
#define SZ(x) ((int)(x).size())
#define fake false



const int di[] = { 0, -1, 0, 1 };
const int dj[] = { 1, 0, -1, 0 };

int main()
{
	//clock_t start, end;
	//start = clock();

	cin.tie(0);
	ios::sync_with_stdio(false);

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

	vector<string> S(H);
	cin >> S;

	vector<pii> points(N + 1);

	const int space = -1;
	const int block = -2;

	vector<vector<int>> board(H, vector<int>(W, space));

	REP(i, H) REP(j, W) {
		if (S[i][j] == 'S') points[0] = pii(i, j);
		else if ('0' <= S[i][j] && S[i][j] <= '9') points[S[i][j] - '0'] = pii(i, j);
		else if (S[i][j] == 'X') board[i][j] = block;
	}

	int ans = 0;
	REP(k, N) {
		pii from = points[k], to = points[k + 1];

		vector<vector<int>> btmp(board);

		queue<pii> qu;
		qu.push(from);
		btmp[from.first][from.second] = 0;

		while (!qu.empty()) {
			pii p = qu.front(); qu.pop();
			int i = p.first, j = p.second;

			int step = btmp[i][j];
			if (p == to) {
				ans += step;
				break;
			}

			REP(d, 4) {
				int ni = i + di[d], nj = j + dj[d];
				if (ni < 0 || H <= ni || nj < 0 || W <= nj) continue;
				if (btmp[ni][nj] == block) continue;
				if (btmp[ni][nj] >= 0 && btmp[ni][nj] <= step) continue;
				btmp[ni][nj] = step + 1;
				qu.push(pii(ni, nj));
			}
		}
	}
	cout << ans << endl;

	//end = clock();
	//printf("%d msec.\n", end - start);

	return 0;
}

C++: 


#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<stack>
#include<queue>
#include<vector>
#include<algorithm>
#include<string>
#include<iostream>
#include<set>
#include<map>

using namespace std;
typedef long long ll;
int mod(ll a){
    int c=a%1000000007;
    if(c>=0)return c;
    else return c+1000000007;
}
typedef pair<int,int> i_i;
typedef pair<ll,ll> l_l;
#define inf 100000000/*10^8*/

/////////////////////////////////



int h,w,n;
char room[1001][1001];
i_i goal[11];
bool done[1001][1001];

int di[4]={1,0,-1,0};
int dj[4]={0,1,0,-1};

int  dfs(int k){
    for(int i=0;i<=h-1;i++)for(int j=0;j<=w-1;j++)done[i][j]=false;
    int si=goal[k].first,sj=goal[k].second;
    int gi=goal[k+1].first,gj=goal[k+1].second;
    queue<i_i> q;
    q.push(make_pair(si,sj));q.push(make_pair(1,0));
    bool whi=true;
    int ans=0;
    while(whi){
        i_i pos=q.front();q.pop();
        i_i count=q.front();q.pop();
        done[pos.first][pos.second]=true;
        for(int i=0;i<=3;i++){
            int ii=pos.first+di[i],jj=pos.second+dj[i];
            if(0<=ii&&ii<=h-1&&0<=jj&&jj<=w-1&&room[ii][jj]!='X'&&done[ii][jj]==false){
                if(ii==gi&&jj==gj)ans=count.first,whi=false;
                else{
                    q.push(make_pair(ii,jj));q.push(make_pair(count.first+1,0));
                }
            }
        }
    }
    
    return ans;
}

int main(){
    cin>>h>>w>>n;
    for(int i=0;i<=h-1;i++)scanf("%s",room[i]);
    for(int i=0;i<=h-1;i++)for(int j=0;j<=w-1;j++){
        if(room[i][j]=='.');
        else if(room[i][j]=='X');
        else if(room[i][j]=='S')goal[0]=make_pair(i,j);
        else goal[room[i][j]-'0']=make_pair(i,j);
    }
    int ans=0;
    for(int i=0;i<=n-1;i++){
        ans+=dfs(i);
    }
    
    cout<<ans<<endl;
    return 0;
}