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++: /*
 *     ____              _    
 *    / __ \____ _____  (_)___ *   / /_/ / __ `/ __ \/ /_  /
 *  / _, _/ /_/ / /_/ / / / /_
 * /_/ |_|\__,_/ .___/_/ /___/
 *            /_/             
 *           code@rapiz.me
 *          Fri, 13 Sep 2019 19:55:31 +0800
 */
#include <bits/stdc++.h>
#define xxx(x) cerr<<(#x)<<": "<<x<<endl;
#define fastios ios::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
typedef long long ll;
using namespace std;
const int N = 1010;
int n, m, dd[4][2] = {
  {1, 0},
  {0, 1},
  {-1, 0},
  {0, -1}
}, fac;
char mm[N][N];
struct Node {
  int x, y, s, hp;
};
queue<Node> q;
bool vis[N][N][10];
int main() {
  cin >> n >> m >> fac;
  Node start;
  for (int i = 1; i <= n; i++) {
    cin >> (mm[i] + 1);
    for (int j = 1; j <= m; j++) {
      if (mm[i][j] == 'S') {
        start.x = i;
        start.y = j;
      }
    }
  }
  start.s = 0;
  start.hp = 1;
  q.push(start);
  while (!q.empty()) {
    Node u = q.front(); q.pop();
    vis[u.x][u.y][u.hp] = 1;
    //xxx(u.x);xxx(u.y);xxx(u.hp);xxx(u.s);
    if (u.hp == fac +1) {
      cout << u.s << endl;
      break;
    }
    for (int i = 0; i < 4; i++) {
      int nx = u.x + dd[i][0], ny = u.y + dd[i][1], nhp = u.hp;
      if (1 <= nx && nx <= n && 1 <= ny && ny <= m){
        if (mm[nx][ny] != 'X') {
          if (mm[nx][ny] >= '1' && mm[nx][ny] <= '9') {
            int idx = mm[nx][ny] - '1' + 1;
            if (u.hp == idx) nhp++;
          }
          if (!vis[nx][ny][nhp]) {
            vis[nx][ny][nhp] = 1;
            q.push((Node){nx, ny, u.s + 1, nhp});
          }
        }
      }
    }
  }
}

C++: //AOJ-0558
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;

char map[1010][1010];
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
int vis[1010][1010];
int m, n, N;
struct node{
	int x, y, t;
};

node bfs(int x, int y, char k)
{
	memset(vis, 0, sizeof(vis));
	queue<node> q;
	node s, e, p;
	s = {x, y, 0};
	q.push(s); vis[x][y] = 1;
	while(!q.empty())
	{
		p = q.front(); q.pop();
		if(map[p.x][p.y] == k) return p;
		for(int i = 0; i < 4; i++)
		{
			int nx = p.x + dx[i];
			int ny = p.y + dy[i];
			if(nx >= n || nx < 0 || ny >= m || ny < 0 || map[nx][ny] == 'X') continue;
			if(!vis[nx][ny]){
				vis[nx][ny] = 1;
				e = {nx, ny, p.t + 1};
				q.push(e);
			}	
		}
	}
}


int main()
{
	while(~scanf("%d %d %d", &n, &m, &N))
	{
		node s;
		for(int i = 0; i < n; i++){
			scanf("%s", map[i]);
			for(int j = 0; j < m; j++){
			   if(map[i][j] == 'S'){
			   	 s.x = i; s.y = j; s.t = 0;
			   }
			}	
		}
		int ans = 0;
		char c = '0';
		for(char i = 1; i <= N; i++)
		{
			node t = bfs(s.x, s.y, c + i);
			ans += t.t;
			s.x = t.x; s.y = t.y;
		}
		printf("%d\n", ans);
	}
	return 0; 
}

C++: #include <iostream>
#include <queue>
#include <cctype>

constexpr int MAX=1000,INF=(int)1e9;

using P=std::pair<int,int>;

int h,w,n;

P poses[9],start;
bool board[MAX][MAX];

int d[MAX][MAX];

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

int bfs(P s,P g){
	for(int i=0;i<h;++i){
		for(int j=0;j<w;++j)
			d[i][j]=INF;
	}
	std::queue<P> que;
	d[s.second][s.first]=0;
	que.emplace(s);

	while(!que.empty()){
		P p=que.front();
		que.pop();
		if(p==g)
			return d[g.second][g.first];
		for(int i=0;i<4;++i){
			int nx=dx[i]+p.first;
			int ny=dy[i]+p.second;
			if(0<=nx&&nx<w&&
				0<=ny&&ny<h&&!board[ny][nx]&&d[ny][nx]==INF){
				d[ny][nx]=d[p.second][p.first]+1;
				que.emplace(nx,ny);
			}
		}
	}
	return -1;
}

int solve() {
	int ans=bfs(start,poses[0]);
	for(int i=1;i<n;++i)
		ans+=bfs(poses[i-1],poses[i]);
	return ans;
}

int main() {
	std::cin>>h>>w>>n;
	char ch;
	for(int i=0;i<h;++i){
		for(int j=0;j<w;++j){
			std::cin>>ch;
			if(ch=='X')
				board[i][j]=true;
			else if(ch=='S')
				start=P(j,i);
			else if(std::isdigit(ch))
				poses[atoi(&ch)-1]=P(j,i);
		}
	}
	std::cout<<solve()<<std::endl;
	return 0;
}