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 <bits/stdc++.h>

#define rep(i,n) for(int i=0, i##_len=(n); i<i##_len; ++i)
#define revrep(i,n) for(int i=(int)(n-1);i>=0;--i)
#define for1(i,a,b) for (int i=(int)a;i<(int)b;++i)

using namespace std;

typedef long long ll;
typedef pair<int, int> P;
typedef map<string, int> m;
typedef vector<int> vi;
typedef vector<string> vs;

const ll MAX_H = 1e3, MAX_W = 1e3, MAX_P = 1e6, mod = 998244353, INF = 1e7;
//qsort
int asc(const void* a, const void* b) {
	return *(int*)a - *(int*)b;
}
//変数置き場
int H, W, N;
char maze[MAX_H][MAX_W + 1];
int sx, sy;
int hp = 1;
int res = 0;
int d[MAX_H][MAX_W];

int dx[4] = { 0,1,0,-1 }; int dy[4] = { 1,0,-1,0 };
void bfs() {
	if (hp > N) return;
	rep(i, H) {
		rep(j, W) d[j][i] = INF;
	}
	queue<P> q;
	q.push(P(sx, sy)); d[sx][sy] = 0;

	while (!q.empty()) {
		P p = q.front(); q.pop();

		rep(i, 4) {
			int nx = p.first + dx[i], ny = p.second + dy[i];

			if (nx >= 0 && nx < W && ny >= 0 && ny < H && maze[nx][ny] != 'X'&& d[nx][ny]==INF) {
				d[nx][ny] = d[p.first][p.second] + 1;
				if (maze[nx][ny] == '0' + hp) {
					res += d[nx][ny];
					sx = nx; sy = ny;
					hp++;
					bfs();
					break;
				}
				q.push(P(nx, ny));
			}
		}
	}
	return;
}

int main() {
	//入力
	cin >> H >> W >> N;
	rep(i, H) {
		rep(j, W) {
			cin >> maze[j][i];
			if (maze[j][i] == 'S') {
				sx = j;
				sy = i;
			}
		}
	}
	bfs();
	cout << res << endl;

	return 0;
}

C++: #include<stdio.h>
#include<queue>
using namespace std;
char sz[1001][1001];
int a,b,c;
struct node{
  int x,y;	
};
typedef struct node Node;
queue<Node>Q;
int bfs(struct node T,int k){
	int cnt=0,flag=1,Flag=1;
	Node vb;
	while(!Q.empty()){
		flag=Flag;
		Flag=0;
	for(int i=0;i<flag;i++){
	for(int dr=-1;dr<=1;dr++){
		for(int dc=-1;dc<=1;dc++){
			if((dc!=0||dr!=0)&&dr*dc==0){
			int xx=Q.front().x+dr;
			int yy=Q.front().y+dc;
			if(xx>=0&&xx<a&&yy>=0&&yy<b){
			if(sz[xx][yy]=='.'||sz[xx][yy]!=k+'0'&&sz[xx][yy]!='X'){
				vb.x =xx;
				vb.y =yy;
				Q.push(vb);
				Flag++;
				sz[xx][yy]=k+'0';
			}
		   if(xx==T.x&&yy==T.y){
		   	while(!Q.empty())Q.pop();
		   	return cnt+1;
		   }
		}
			}
		}
	}
	Q.pop();
}
cnt++;
}
return cnt;
}
int main(){
	
	struct node st[10];
	while(scanf("%d%d%d",&a,&b,&c)){
		getchar();
		for(int i=0;i<a;i++){
			for(int j=0;j<b;j++){
				scanf("%c",&sz[i][j]);
				if(sz[i][j]=='S'){ st[0].x=i;st[0].y=j;sz[i][j]='0';}
				if(sz[i][j]>'0'&&sz[i][j]<='9'){st[sz[i][j]-'0'].x=i;st[sz[i][j]-'0'].y =j;}
			}
			getchar();
		}
		int count=0;
		for(int i=1;i<=c;i++){
			Q.push(st[i-1]);
			count+=bfs(st[i],i-1);
		}
		printf("%d\n",count);
	}
	
}

C++: #include <bits/stdc++.h>
#define err(args...) {}
#ifdef DEBUG
#include "_debug.cpp"
#endif
using namespace std;
using ll = long long;
template <typename signature> using f = const function<signature>;
f<bool(int, int)> hori = [](int di, int dj) { return abs(di) == 0 and abs(dj) == 1; };
f<bool(int, int)> vert = [](int di, int dj) { return abs(di) == 1 and abs(dj) == 0; };
f<bool(int, int)> diag = [](int di, int dj) { return abs(di) == 1 and abs(dj) == 1; };
f<bool(int, int)> operator||(f<bool(int, int)>& f1, f<bool(int, int)>& f2) {
    return [&](int di, int dj) { return f1(di, dj) or f2(di, dj); };
}
vector<vector<int>> flood(vector<vector<int>>& a, int si, int sj,
f<bool(int, int)>& can, f<void(int, int)>& f = [](int, int) {}) {
    vector<vector<int>> d(a.size(), vector<int>(a[0].size(), -1));
    d[si][sj] = 0;
    queue<pair<int, int>> q({{si, sj}});
    while(not q.empty()) {
        auto p = q.front(); q.pop();
        int i = p.first, j = p.second;
        f(i, j);
        for(int di = -1; di <= 1; di++) {
            for(int dj = -1; dj <= 1; dj++) {
                int ni = i + di, nj = j + dj;
                if(a[ni][nj] and d[ni][nj] == -1 and can(di, dj)) {
                    d[ni][nj] = d[i][j] + 1;
                    q.push({ni, nj});
                }
            }
        }
    }
    return d;
}
int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    int h, w, n;
    cin >> h >> w >> n;
    vector<vector<int>> a(h + 2, vector<int>(w + 2));
    vector<int> vi(n + 1), vj(n + 1);
    for(int i = 1; i <= h; i++) {
        string s;
        cin >> s;
        for(int j = 1; j <= w; j++) {
            a[i][j] = s[j - 1] != 'X';
            if(s[j - 1] == 'S') {
                vi[0] = i, vj[0] = j;
            } else if(isdigit(s[j - 1])) {
                vi[s[j - 1] - '0'] = i, vj[s[j - 1] - '0'] = j;
            }
        }
    }
    int ans = 0;
    for(int i = 1; i <= n; i++) {
        ans += flood(a, vi[i - 1], vj[i - 1], hori or vert)[vi[i]][vj[i]];
    }
    cout << ans << endl;
    return 0;
}

C++: #include <iostream>
#include <stdio.h>
#include <string>
#include <map>
#include <stack>
#include <vector>
#include <string.h>
#include <set>
#include <queue>
#include <cmath>
#include <algorithm>

using namespace std;

struct node
{
	int x;
	int y;
	int dist;

	node(int x , int y , int dist)
	{
		this -> x = x;
		this -> y = y;
		this -> dist = dist;
	}
};

bool vis[1010][1010];
char input[1010][1010];
int dx[4] = {- 1 , 0 , 1 , 0};
int dy[4] = {0 , 1 , 0 , - 1};
queue<node> q;

bool inArea(int x , int y , int n , int m)
{
	return x >= 0 && x < n && y >= 0 && y < m;
}

int solve(int sx , int sy , int h , int w , int n)
{
	while (!q.empty())
		q.pop();

	int value = 1;
	q.push(node(sx , sy , 0));
	vis[sx][sy] = true;

	while (!q.empty())
	{
		node no = q.front();
		q.pop();

		if (input[no.x][no.y] >= '0' && input[no.x][no.y] <= '9' && ((input[no.x][no.y] - '0') == value))
		{
			value ++;
			if (value == n + 1)
				return no.dist;

			while (!q.empty())
				q.pop();

			for (int i = 0;i < h;i ++)
				for (int j = 0;j < w;j ++)
					vis[i][j] = false;
			vis[no.x][no.y] = true;
		}
		for (int i = 0;i < 4;i ++)
		{
			int tx = no.x + dx[i];
			int ty = no.y + dy[i];
			if (inArea(tx , ty , h , w) && !vis[tx][ty] && input[tx][ty] != 'X')
			{
				vis[tx][ty] = true;
				q.push(node(tx , ty , no.dist + 1));
			}
		}
	}
	return - 1;
}

int main()
{
	int i , j , h , w , n;
	while (scanf("%d%d%d" , &h , &w , &n) != EOF)
	{
		for (i = 0;i < h;i ++)
			for (j = 0;j < w;j ++)
				vis[i][j] = false;

		int sx , sy;
		for (i = 0;i < h;i ++)
		{
			scanf("%s" , input[i]);
			for (j = 0;j < w;j ++)
			{
				if (input[i][j] == 'S')
				{
					sx = i;
					sy = j;
				}
			}
		}

		// ???S????§????
		printf("%d\n" , solve(sx , sy , h , w , n));
	}
	return 0;
}