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 <cstring>
#include <queue>
#include <algorithm>
#include <cstdio>

#define INF 1 << 29

using namespace std;

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

class S{
public:
    int x;
    int y;
    int lvl;
    int step;

    S(int x, int y, int lvl, int step):x(x),y(y),lvl(lvl),step(step){}
};

int main(){
    int h,w,lvl,sx,sy,gx,gy;
    cin >> h >> w >> lvl;
    char f[h+2][w+2];
    int visited[h+2][w+2][lvl+1];
    fill((char *)f, (char *)f+(h+2)*(w+2), 'X');
    fill((int *)visited, (int *)visited+(h+2)*(w+2)*(lvl+1), INF);

    for(int i=1;i<=h;i++){
        for(int j=1;j<=w;j++){
            cin >> f[i][j];
            if(f[i][j] == 'S'){
                sx = j;
                sy = i;
            }else if(f[i][j] == lvl + '0'){
                gx = j;
                gy = i;
            }
        }
    }
    deque<S> q;
    q.push_back(S(sx,sy,1,0));
    visited[sy][sx][1] = 0;
    int px,py,tmplvl,tmpstep;
    while(!q.empty()){
        px = q.front().x;
        py = q.front().y;
        tmplvl = q.front().lvl;
        tmpstep = q.front().step;
        q.pop_front();

        //printf("current:(y = %d, x = %d, lvl = %d, step = %d)\n", py,px,tmplvl,tmpstep);

        if(py == gy && px == gx && tmplvl == lvl+1){
            break;
        }
        visited[py][px][tmplvl] = tmpstep;
        for(int i=0;i<4;i++){
            int nx = px + dx[i];
            int ny = py + dy[i];

            if(f[ny][nx] != 'X'){
                if(f[ny][nx] == tmplvl +'0'){
                    q.push_back(S(nx,ny,tmplvl+1,tmpstep+1));
                }else{
                    if(tmpstep + 1 < visited[ny][nx][tmplvl]){
                        q.push_back(S(nx,ny,tmplvl,tmpstep+1));
                        visited[ny][nx][tmplvl] = tmpstep+1;
                    }
                }
            }
        }
    }
    cout << tmpstep << endl;
}

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;
	vis[x][y] = 1;
	node s, e, p; s.x = x; s.y = y; s.t = 0;
	q.push(s);
	while(!q.empty())
	{
		p = q.front(); q.pop();
		vis[p.x][p.y] = 1;
		if(map[p.x][p.y] == k) return p;
		for(int i = 0; i < 4; i++)
		{
			e.x = p.x + dx[i];
			e.y = p.y + dy[i];
			if(e.x >= n || e.x < 0 || e.y >= m || e.y < 0 || map[e.x][e.y] == 'X' || vis[e.x][e.y] == 1) continue;
			e.t = p.t + 1;
			q.push(e);
		}
	}
}


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

C++: #include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <string>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <algorithm>

using namespace std;

#define rep(i,j) REP((i), 0, (j))
#define REP(i,j,k) for(int i=(j);(i)<(k);++i)
#define BW(a,x,b) ((a)<=(x)&&(x)<=(b))
#define ALL(v) (v).begin(), (v).end()
#define LENGTHOF(x) (sizeof(x) / sizeof(*(x)))
#define AFILL(a, b) fill((int*)a, (int*)(a + LENGTHOF(a)), b)
#define MP make_pair
#define PB push_back
#define F first
#define S second
#define Y first
#define X second
#define INF 1 << 30
#define EPS 1e-10

typedef pair<int, int> pi;
typedef pair<int, pi> pii;
typedef pair<pi, pi> pipi;
typedef vector<int> vi;
typedef queue<int> qi;
typedef long long ll;

int H, W, N;
char field[1000][1000];
int dy[] = {0,1,0,-1}, dx[] = {1,0,-1,0};

int main(){
  scanf("%d%d%d", &H, &W, &N);
  rep(i, H) scanf("%s", field[i]);

  int x, y;
  rep(i, H) rep(j, W) if(field[i][j] == 'S'){ y = i; x = j; break;}
  pii p;
  p = MP(0, MP(y, x));
  REP(i, 1, N+1){
    map<pi, int>m;
    m[MP(p.S.Y, p.S.X)] = 1;
    queue<pii>q;
    q.push(MP(p.F, MP(p.S.Y, p.S.X)));
    while(!q.empty()){
      p = q.front(); q.pop();
      if(field[p.S.Y][p.S.X] == i + '0'){
	break;
      }
      rep(d, 4){
	int ny = p.S.Y + dy[d], nx = p.S.X + dx[d];
	int c = p.F;
	if(ny < 0 || ny >= H || nx < 0 || nx >= W || field[ny][nx] == 'X') continue;
	if(m.count(MP(ny, nx))) continue;

	m[MP(ny, nx)] = 1;
	q.push(MP(c+1, MP(ny, nx)));
      }
    }
  e:
    if(i == N)  printf("%d\n", p.F);
  }
  return 0;
}

C++: #include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <string>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <algorithm>

using namespace std;

#define rep(i,j) REP((i), 0, (j))
#define REP(i,j,k) for(int i=(j);(i)<(k);++i)
#define BW(a,x,b) ((a)<=(x)&&(x)<=(b))
#define ALL(v) (v).begin(), (v).end()
#define LENGTHOF(x) (sizeof(x) / sizeof(*(x)))
#define AFILL(a, b) fill((int*)a, (int*)(a + LENGTHOF(a)), b)
#define MP make_pair
#define PB push_back
#define F first
#define S second
#define INF 1 << 30
#define EPS 1e-10

typedef pair<int, int> pi;
typedef pair<pi, int> pii;
typedef pair<pi, pi> pipi;
typedef vector<int> vi;
typedef queue<int> qi;
typedef long long ll;

int H, W, N;
char g[1024][1024];
int dy[] = {0,-1,0,1}, dx[] = {-1,0,1,0};

int main(){
  scanf("%d%d%d", &H, &W, &N);
  rep(i, H) scanf("%s", g[i]);

  int y, x;
  rep(i, H) rep(j, W) if(g[i][j] == 'S') y = i, x = j;

  queue<pipi>q;
  q.push(MP(MP(y, x), MP(1, 0))); // y, x, hp, time
  map<pii, int>m;
  m[MP(MP(y, x), 1)] = 1;

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

    int hp = p.S.F;
    if(g[p.F.F][p.F.S] - '0' == hp){
      while(!q.empty()) q.pop();
      hp++;
    }

    if(hp > N){
      printf("%d\n", p.S.S);
      break;
    }

    rep(d, 4){
      int ny = p.F.F+dy[d], nx = p.F.S+dx[d];
      if(ny < 0 || ny >= H || nx < 0 || nx >= W || g[ny][nx] == 'X' || m.find(MP(MP(ny, nx), hp)) != m.end()) continue;
      q.push(MP(MP(ny, nx), MP(hp, p.S.S+1)));
      m[MP(MP(ny, nx), hp)] = 1;
    }
  }
  return 0;
}