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 <vector>
#include <string>
#include <cstdlib>
#include <algorithm>
#include <functional>
using namespace std;

#define START 10
#define CANTGO 0
#define NONE 11
#define _HAS_ITERATOR_DEBUGGING 0

struct Point
{
	int x;
	int y;
};

int dx[] = {0,-1,0,1};//ã©çvñè
int dy[] = {1,0,-1,0};

int field[1001][1001];
int mfield[1001][1001] = {};
int life=1;
int counter=0;
int csum = 0;

int open(vector<Point> &sp,vector<Point> &tp)
{
	counter++;
	int i,j;
	Point inp;

	tp.clear();

	for(i=0;i<sp.size();i++)
	{
		for(j=0;j<4;j++)
		{
			inp.x = sp[i].x+dx[j];
			inp.y = sp[i].y+dy[j];

			if(field[inp.x][inp.y] != CANTGO && field[inp.x][inp.y] != START && inp.x>=0 && inp.y>=0)
			{
				if(mfield[inp.x][inp.y] == 0)
				{
					//v·éÉÅZ£Ú®Â\][]
					if(field[inp.x][inp.y] == life) //©ªÉ©Á½`[YÌ­©
					{
						sp.clear();
						sp.push_back(inp);
						return counter;
					}
					else
					{
						tp.push_back(inp);
						mfield[inp.x][inp.y] = counter;
					}
				}
			}
		}
	}

	sp.clear();
	sp.reserve(1000);//ÌmÛ	
	//copy(tp.begin() , tp.end() , sp.begin());
	for(i=0;i<tp.size();i++)
	{
		sp.push_back(tp[i]);
	}
	return 0;
}

int main(void)
{
	int H,W,N;
	int i,j;
	string instr[1000];
	vector<Point> sp;
	vector<Point> tp;
	Point inp;
	int count = 0;
	cin >> H >> W >> N;

	for(i=0;i<H;i++)//üÍ
	{
		cin >> instr[i];
		for(j=0;j<W;j++)
		{
			if(instr[i][j] == 'S')
			{
				field[i][j] = START;
				inp.x = i;
				inp.y = j;
				sp.push_back(inp);
			}
			else if(instr[i][j] == 'X')
				field[i][j] = CANTGO;
			else if(instr[i][j] == '.')
				field[i][j] = NONE;
			else
				field[i][j] = instr[i][j] - '0';
		}
	}//üÍIíè

	while(1)
	{
		if(open(sp,tp) != 0)
		{
			life++;
			for(i=0;i<1001;i++)
			{
				for(j=0;j<1001;j++)
				{
					mfield[i][j] = 0;
				}
			}
			csum += counter;
			counter = 0;
		}
		if(life > N)
			break;
	}
	cout << csum << endl;



	return 0;
}

C++: #include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <set>
#include <map>
#include <string>
#include <stack>
#include <queue>
#include <cmath>
#include <cstdio>
#include <istream>
#include <sstream>
#include <iomanip>
#include <iterator>
#include <climits>
using namespace std;

typedef ostringstream OSS;
typedef istringstream ISS;

typedef vector<int> VI;
typedef vector< VI > VVI;

typedef long long LL;

typedef pair<int, int> PII;
typedef vector<PII> VPII;

#define Y first
#define X second

int H, W, N;
vector<string> ts;

int main(void) {
	cin >> H >> W >> N;
	ts = vector<string>(H);
	for (auto &line : ts) cin >> line;

	string seq(N, '0');
	iota(seq.begin(), seq.end(), '1');
	
	PII start;
	for (int y = 0; y < H; y++) {
		for (int x = 0; x < W; x++) {
			if (ts[y][x] == 'S') {
				start.Y = y;
				start.X = x;
			}
		}
	}

	int total_time = 0;
	queue<pair<int, PII>> q;
	q.push(make_pair(0, start));
	vector<vector<bool>> done(H, vector<bool>(W));

	for (int i = 0; i < N; i++) {
		while(q.size()) {
			int now = q.front().first;
			int y = q.front().second.Y;
			int x = q.front().second.X;
			q.pop();

			if (done[y][x]) continue;
			done[y][x] = true;

			if (ts[y][x] == seq[i]) {
				q = queue<pair<int, PII>>();
				q.push(make_pair(0, make_pair(y, x)));
				done = vector<vector<bool>>(H, vector<bool>(W));
				total_time += now;
				break;
			}

			for (int dx = -1; dx <= 1; dx++) {
				for (int dy = -1; dy <= 1; dy++) {
					if (!(!dx ^ !dy)) continue;
					int nx = x + dx;
					int ny = y + dy;

					if (nx < 0 || ny < 0 || nx >= W || ny >= H) continue;
					if (done[ny][nx]) continue;
					if (ts[ny][nx] == 'X') continue;

					if (!done[ny][nx]) {
						q.push(make_pair(now + 1, make_pair(ny, nx)));
					}
				}
			}
		}
	}

	cout << total_time << endl;
	

	return 0;
}

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[1001][1001];
int ix, iy,x,y;
int te[1001][1001];
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++: #include <iostream>
#include <algorithm>
#include <queue>
#include <cstring>
using namespace std;
#define MAX 1005

char JOI[MAX][MAX];
int h,w,n;
int dx[]={0,-1,0,1};
int dy[]={1,0,-1,0};

pair<int, int> goal[10];
bool check(int a,int b){
    return (a>=1&&a<=h&&b>=1&&b<=w);
}

int step[MAX][MAX];
int bfs(pair<int, int> st,pair<int, int> en){
    queue<pair<int,int> > q;
    q.push(st);
    memset(step, -1, sizeof(step));
    step[st.first][st.second]=0;
    int stp=0;
    while(!q.empty()){
        pair<int, int> S=q.front(); q.pop();
        int x=S.first;  int y=S.second;
        stp=step[x][y];
        for(int i=0; i<4; i++){
            int cx=x+dx[i]; int cy=y+dy[i];
            if(check(cx, cy)){
                if(JOI[cx][cy]!='X'&&step[cx][cy]==-1){
                    if(cx==en.first&&cy==en.second) return stp+1;
                    q.push(make_pair(cx, cy));
                    step[cx][cy]=stp+1;
                }
            }
        }
    }
}
int main(){
    cin>>h>>w>>n;
    for(int i=1; i<=h; i++){
        for(int j=1; j<=w; j++){
            cin>>JOI[i][j];
            if(JOI[i][j]=='S') goal[0]=make_pair(i, j);
            else if(JOI[i][j]>='0'&&JOI[i][j]<='9'){
                int x=JOI[i][j]-'0';
                goal[x]=make_pair(i, j);
            }
        }
    }
    int ans=0;
    for(int i=0; i<n; i++){
        ans+=bfs(goal[i],goal[i+1]);
    }
    cout<<ans<<endl;
}