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>
using namespace std;

const int inf = 1e9;
typedef pair<int,int> P;
typedef pair<int, P> PP;
int dy[] = {-1, 0, 0, 1};
int dx[] = {0, -1, 1, 0};
struct BFS_Maze{
	vector<vector<int> > d, a;
	int sy, sx, ey, ex, h, w;
	void init(int inputH, int inputW){
		h = inputH, w = inputW;
		d.resize(h+2);
		a.resize(h+2);
		for(int i = 0;i < h+2;i++){
			d[i].resize(w+2);
			a[i].resize(w+2);
		}
	}
	
	void insertion(int y, int x, int v){a[y][x] = v;}
	void start(int y, int x){sy = y;sx = x;}
	void end(int y, int x){ey = y;ex = x;}
	
	int calc(){
		for(int i = 0;i < h+2;i++)d[i].assign(w+2, inf);
		queue<P> q;
		q.push(P(sy, sx));
		d[sy][sx] = 0;
		while(!q.empty()){
			P p = q.front();q.pop();
			int y = p.first, x = p.second;
			if(y == 0 || x == 0)continue;
			if(y == h+1 || x == w+1)continue;
			for(int i = 0;i < 4;i++){
				int yy = y+dy[i], xx = x+dx[i];
				if(d[yy][xx] > d[y][x]+1 && a[yy][xx] == 0){
					d[yy][xx] = d[y][x]+1;
					q.push(P(yy, xx));
				}
			}
		}
		return d[ey][ex];
	}
};

#define rep(i,n) for(int i = 0;i < n;i++)
#define rrep(i,n) for(int i = 1;i <= n;i++)
#define fi first
#define se second

char str[1010][1010];
int a[1010][1010];
int main(){
	BFS_Maze BM;
	int h, w, n;
	vector<PP> v;
	scanf("%d%d%d", &h, &w, &n);
	rep(i,h)scanf("%s", str[i]);
	BM.init(h, w);
	
	rep(i,h)rep(j,w){
		if(str[i][j] == 'S'){
			v.push_back(PP(0, P(i+1, j+1)));
		}else if(str[i][j] == 'X'){
			BM.insertion(i+1, j+1, 1);
		}else if(str[i][j] == '.'){
			BM.insertion(i+1, j+1, 0);
		}else{
			v.push_back(PP(str[i][j]-'0', P(i+1, j+1)));
		}
	}
	sort(v.begin(), v.end());
	
	int ans = 0;
	for(int i = 0;i < v.size()-1;i++){
		int y = v[i].se.fi, x = v[i].se.se;
		int yy = v[i+1].se.fi, xx = v[i+1].se.se;
		//M.init(h, w);
		BM.start(y, x);
		BM.end(yy, xx);
		int v = BM.calc();
		ans += v;
	}
	printf("%d\n", ans);
	return 0;
}

C++: #include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cfloat>
#include <map>
#include <utility>
#include <set>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
#include <sstream>
#include <complex>
#include <stack>
#include <queue>
#include <cstring>
#include <sstream>
#include <cassert>
using namespace std;
static const double EPS = 1e-10;
typedef long long ll;
typedef pair<int,int> PI;
#define rep(i,n) for(int i=0;i<(int)n;++i)
#define FOR(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i)
#define ALL(c) (c).begin(), (c).end()
#define mp(a,b) make_pair(a,b)
#define pb(a) push_back(a)
int dx[]={0,1,0,-1},dy[]={1,0,-1,0};

typedef struct{
  short x,y;
  int cost;
  short ch;
}mouse;

short maxch[1000][1000];
char ku[1000][1000];
mouse t;
short cx,cy,nx,ny,ch,nch,h,w,n;
int cost;

main(){
  scanf("%d%d%d",&h,&w,&n);

  rep(i,h)scanf("%s",ku[i]);


  rep(i,h)rep(j,w){
    if(ku[i][j]=='S')cx=i,cy=j;
    maxch[i][j]=-1;
  }

  queue<mouse> Q;

  Q.push((mouse){cx,cy,0,0});
  maxch[cx][cy]=0;

  while(!Q.empty()){
    //cout<<Q.size()<<endl;
    t=Q.front();Q.pop();
    cx=t.x,cy=t.y,cost=t.cost;
    ch=t.ch;

    rep(i,4){
      nx=cx+dx[i],ny=cy+dy[i];
      if(nx<0 || nx>=h || ny<0 || ny>=w)continue;
	 if(ku[nx][ny]=='X')continue;
	 nch=ch;
	 if(ku[nx][ny]<='9' && ku[nx][ny]>='1' && ku[nx][ny]-'0'==t.ch+1){
	   nch=ch+1;
	 }

	 if(maxch[nx][ny]>=nch)continue;
	 if(nch==n){
	   printf("%d\n",cost+1);
	   return 0;
	 }
	 maxch[nx][ny]=nch;
	 Q.push((mouse){nx,ny,cost+1,nch});
    }
  }
}

C++: #include <bits/stdc++.h>

using namespace std;
typedef pair<int, int> p;
char maze[1000][1000];
int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};
int h, w, n;
char tem[] = "S123456789";
int dis[1000][1000];
p st[10];

int bfs(p, p);

int main() {
    cin >> h >> w >> n;
    for (int i = 0; i < h; i++)
        for (int t = 0; t < w; t++) {
            cin >> maze[i][t];
            for (int j = 0; j <= n; j++) {
                if (maze[i][t] == tem[j])
                    st[j] = p(i, t);//????????
            }
        }
    int ans = 0;
    for (int i = 1; i <= n; i++) {//????
        memset(dis, -1, sizeof(dis));
        ans += bfs(st[i - 1], st[i]);
    }
    cout << ans << endl;
    return 0;
}

int bfs(p start, p ending) {
    queue<p> que;
    que.push(start);
    dis[start.first][start.second] = 0;
    while (!que.empty()) {
        p now = que.front();
        que.pop();
        if (now == ending)
            break;
        for (int i = 0; i < 4; i++) {
            int nx = now.first + dx[i];
            int ny = now.second + dy[i];
            if (nx >= 0 && nx < h && 0 <= ny && ny < w && dis[nx][ny] == -1 && maze[nx][ny] != 'X') {
                que.push(p(nx, ny));
                dis[nx][ny] = dis[now.first][now.second] + 1;
            }
        }
    }
    return dis[ending.first][ending.second];
}

C++: #include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cfloat>
#include <map>
#include <utility>
#include <set>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
#include <sstream>
#include <complex>
#include <stack>
#include <queue>
#include <cstring>
#include <sstream>
#include <cassert>
using namespace std;
static const double EPS = 1e-10;
typedef long long ll;
typedef pair<int,int> PI;
#define rep(i,n) for(int i=0;i<(int)n;++i)
#define FOR(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i)
#define ALL(c) (c).begin(), (c).end()
#define mp(a,b) make_pair(a,b)
#define pb(a) push_back(a)
int dx[]={0,1,0,-1},dy[]={1,0,-1,0};

typedef struct{
  short x,y;
  int cost;
  short ch;
}mouse;


mouse t;
short cx,cy,nx,ny,ch,nch,h,w,n;
int cost;

main(){
  scanf("%d%d%d",&h,&w,&n);
  short maxch[h][w];
  char ku[h][w];
  
  rep(i,h)scanf("%s",ku[i]);


  rep(i,h)rep(j,w){
    if(ku[i][j]=='S')cx=i,cy=j;
    maxch[i][j]=-1;
  }

  queue<mouse> Q;

  Q.push((mouse){cx,cy,0,0});
  maxch[cx][cy]=0;

  while(!Q.empty()){
    //cout<<Q.size()<<endl;
    t=Q.front();Q.pop();
    cx=t.x,cy=t.y,cost=t.cost;
    ch=t.ch;

    rep(i,4){
      nx=cx+dx[i],ny=cy+dy[i];
      if(nx<0 || nx>=h || ny<0 || ny>=w)continue;
	 if(ku[nx][ny]=='X')continue;
	 nch=ch;
	 if(ku[nx][ny]<='9' && ku[nx][ny]>='1' && ku[nx][ny]-'0'==t.ch+1){
	   nch=ch+1;
	 }

	 if(maxch[nx][ny]>=nch)continue;
	 if(nch==n){
	   printf("%d\n",cost+1);
	   return 0;
	 }
	 maxch[nx][ny]=nch;
	 Q.push((mouse){nx,ny,cost+1,nch});
    }
  }
}