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<algorithm>
#include<stdio.h>
#include<queue>
using namespace std;
queue<pair<int, int>>q;
pair <int, int>p;
pair <int, int> po;
int n, m,c;
char ma[101][101];
int ix, iy,x,y;
int te[101][101];
int xw[4] = { 1, 0, -1, 0 };
int yw[4] = { 0, 1, 0, -1 };
char name[10] = { '1', '2', '3', '4', '5', '6', '7', '8', '9' };
int nat = 0;
int na;
int op = 10000;
int main()
{
	cin >> n >> m>>na;
	for (int i = 0; i < n; i++){
		for (int i2 = 0; i2 < m; i2++){
			cin >> ma[i][i2];
			te[i][i2] = op;
			if (ma[i][i2] == 'S'){
				p.first = i;
				p.second = i2;
			}
		}
	}
	
	int count;

	count = 0;
	q.push(p);
	
	te[p.first][p.second] = 0;
	while (!q.empty()){
		p = q.front();
		po = p;
		q.pop();
		
		for (int i = 0; i < 4; i++){
			x = p.first + xw[i];
			y = p.second + yw[i];
			if (0<=x && x<=n&&0<=y && y<=m&&ma[x][y] != 'X'&&te[x][y] == op){

				if (ma[x][y] == name[nat]){
					po.first = x;
					po.second = y;
					while (!q.empty()){ q.pop(); }
					q.push(po);
					po = p;
					count += te[p.first][p.second] + 1;
					nat++; 
					if (nat == na){ cout << count << endl; return 0; }
					//memset(te, op, sizeof(te));
					for (int i2 = 0; i2 <= n; i2++){
						for (int i3 = 0; i3 <= m; i3++){
							te[i2][i3] = op;
						}
					}
					te[x][y] = 0;
					break;
				}

				else{
					po.first = x;
					po.second = y;
					q.push(po);
					po = p;
					te[x][y] = te[p.first][p.second] + 1;
				}
			}
		}
	}
}

C++: // clang-format off
#include <bits/stdc++.h>
#define int long long
#define main signed main()
// #define main int main()
#define loop(i, a, n) for (int i = (a); i < (n); i++)
#define rep(i, n) loop(i, 0, n)
#define all(v) (v).begin(), (v).end()
#define rall(v) (v).rbegin(), (v).rend()
#define prec(n) fixed << setprecision(n)
#define stlice(from, to) substr(from, (to) - (from) + 1)
#define pb push_back
#define mp make_pair
#define mt make_tuple
#define fi first
#define se second
using namespace std;
typedef pair<int, int> pii;
typedef vector<int> vi;
typedef vector<double> vd;
typedef vector<char> vc;
typedef vector<bool> vb;
typedef vector<string> vs;
typedef vector<pii> vpii;
typedef vector<vi> vvi;
typedef vector<vb> vvb;
typedef vector<vpii> vvpii;
const int INF = sizeof(int) == sizeof(long long) ? 1000000000000000000LL : 1000000000;
const int MOD = 1000000007;
const double PI = acos(-1);
template<typename A, typename B> bool cmin(A &a, const B &b) { return a > b ? (a = b, true) : false; }
template<typename A, typename B> bool cmax(A &a, const B &b) { return a < b ? (a = b, true) : false; }
bool odd(const int &n) { return n & 1; }
bool even(const int &n) { return !odd(n); }
void solve();
main { solve(); return 0; }
// clang-format on

typedef pair<pii, int> ppi;

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

void solve() {
  int h, w, n;
  cin >> h >> w >> n;
  vs s(h);
  vpii v(n + 1);
  rep(i, h) {
    cin >> s[i];
    rep(j, w) {
      if (s[i][j] == 'S') v[0]                               = mp(i, j);
      if ('1' <= s[i][j] && s[i][j] <= '9') v[s[i][j] - '0'] = mp(i, j);
    }
  }
  int c    = 0;
  auto bfs = [&](vs s, pii f, pii t) {
    queue<ppi> q;
    q.push(mp(f, 0));
    while (q.size()) {
      int i = q.front().fi.fi, j = q.front().fi.se, d = q.front().se;
      q.pop();
      if (i < 0 || j < 0 || i >= h || j >= w || s[i][j] == 'X') continue;
      if (i == t.fi && j == t.se) return d;
      s[i][j] = 'X';
      d++;
      rep(k, 4) q.push(mp(mp(i + di[k], j + dj[k]), d));
    }
  };
  loop(i, 1, v.size()) c += bfs(s, v[i - 1], v[i]);
  cout << c << endl;
}

C++: #include <iostream>
#include <string.h>
#include <fstream>
#include<time.h>
#include <string>
#include <string.h>
#include <vector>
#include <stdio.h>
#include <cstdlib>
#include <stack>
#include <map>
#include <queue>
#include<cctype>
#include <math.h>
#include <algorithm>
#define Size 1005
using namespace std;
char flo[Size][Size];
int mark[Size][Size];
typedef pair<int, int> node;
int dir_x[]={ 0, 0, 1, -1};
int dir_y[]={ 1, -1, 0, 0};
int h, w, n, _count;
bool check(int x,int y,char _size, int next_stp){
    if(x < 0|| x >= h || y < 0 || y >= w)
        return false;
    if(flo[x][y] == 'X')
        return false;
    if(next_stp <= mark[x][y] || mark[x][y] == 0)
        return true;
    else
        return false;
}
void bfs(int sx, int sy){
    queue<node> que;
    que.push(node(sx, sy));
    char _size = '1';
    while(!que.empty() && n != 0){
        node temp = que.front();
        que.pop();
        int x = temp.first, y = temp.second;
        if(flo[x][y] >= '1' && flo[x][y] <= '9'){
            if(flo[x][y] <= _size){
                flo[x][y] = '.';
                _count += mark[x][y];
                memset(mark, 0 , sizeof(mark));
                while(!que.empty())
                    que.pop();
                n --; _size ++;
                mark[x][y] = 0;
            }
        }
        int next_stp = mark[x][y] + 1;
        for(int i = 0; i < 4; i ++){
            int t_x = x + dir_x[i], t_y = y +dir_y[i];
            if(check(t_x, t_y , _size, next_stp)){
                que.push(node(t_x,t_y));
                mark[t_x][t_y] = next_stp;
            }
        }
    }
}
int main()
{
    ifstream in;
    in.open("a.txt", ios::in);
    in>>h>>w>>n;
    int begin_x, begin_y;
    memset(mark, 0, sizeof(mark));
    for(int i = 0; i < h; i ++){
        for(int j = 0; j < w; j ++){
            in>>flo[i][j];
            if(flo[i][j] == 'S'){
                begin_x = i;
                begin_y = j;
                mark[i][j] = 0;
                flo[i][j] = '.';
            }
        }
    }
    _count = 0;
    bfs(begin_x, begin_y);
    cout<<_count<<endl;
    return 0;
}