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++: //AOJ 0558
//include
#include<bits/stdc++.h>

//using
using namespace std;


//define static const typedef
#define FOR(i, s, n) for(int i = s; i < int(n); i++)
#define REP(i, n) FOR((i), 0, (n))
#define ALL(a) (a).begin(), (a).end()
#define RALL(a) (a).rbegin(), (a).rend()
#define PB push_back
#define MP make_pair
#define SORT(a) sort(ALL(a))
#define RSORT(a) sort(RALL(a))
#define DUMP(x) cerr << #x << " = " << x << "\n";
#define DEBUG(x) cerr << #x << " = " << x << " (L:" << __LINE__ << ") " << __FILE__ << "\n";
#define F first
#define S second

typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<string> VS;
typedef pair<int, int> PII;
typedef vector<PII> VPII;
typedef long long LL;
typedef vector<LL> VLL;
typedef vector<VLL> VVLL;
typedef unsigned long long ULL;

static const int INF = 1 << 25;
static const int movex[] = {0,0,1,-1};
static const int movey[] = {1,-1,0,0};
//global
int a, b, c, ans, hp = 1;
VS mp;
int sx = INF, sy = INF;
string str = "";
char inp[1000];
vector<VVI> ar;
queue<pair<int, PII > >  n;
//function
int main(){
  scanf("%d %d %d", &a, &b, &c);
  REP(i, b + 2){
    str = str + "X";
  }
  mp.PB(str);
  REP(i, a){
    scanf("%s", inp);
    mp.PB(inp);
    mp[i + 1] = "X" + mp[i + 1] + "X";
    REP(j, mp[i + 1].size()){
      if(sx != INF){
	break;
      }
      if(mp[i + 1][j] == 'S'){
	sy = i + 1;
	sx = j;
	break;
      }
    }
  }
  ar.resize(c, VVI(a + 2, VI(b + 2)));
  REP(i, c){
    REP(j, a + 2){
      REP(k, b + 2){
	ar[i][j][k] = INF;
	if(!i && sy == j && sx == k){
	  ar[0][j][k] = 0;
	}
      }
    }
  }
  mp.PB(str);
  n.push(pair<int, PII>(hp, PII(sy, sx)));

  while(!n.empty()){
    if(n.front().F != hp){
      n.pop();
      continue;
    }
    if(hp == mp[n.front().S.F][n.front().S.S] - '0'){
      hp++;
      if(hp > c){
	ans = ar[c - 1][n.front().S.F][n.front().S.S];
	break;
      }
      ar[hp - 1][n.front().S.F][n.front().S.S] = ar[hp - 2][n.front().S.F][n.front().S.S];
    }
    int nowy = n.front().S.F, nowx = n.front().S.S;
    n.pop();
    REP(i, 4){
      if(mp[nowy + movey[i]][nowx + movex[i]] != 'X' && ar[hp - 1][nowy + movey[i]][nowx + movex[i]] > ar[hp - 1][nowy][nowx] + 1){
	ar[hp - 1][nowy + movey[i]][nowx + movex[i]] = ar[hp - 1][nowy][nowx] + 1;
	n.push(pair<int, PII>(hp, PII(nowy + movey[i], nowx + movex[i])));
      }
    }
  }
  printf("%d\n",ans);
  return 0;
}

C++: //待解，&#35843;用函数 
#include<queue>
#include<cctype>
#include<cstdio>
#define mp          make_pair
using namespace std;
typedef pair<int,int> point;
const int maxn = 1005;
int height,width;    //n代表硬度 
char maze[maxn][maxn];
const int dx[]={1,0,-1,0},dy[]={0,-1,0,1};

bool visited[maxn][maxn];
int shortDistance(int sx,int sy,int ex,int ey)
{
	//初始化visted数&#32452;
	for(int i = 0;i<height;i++)
		for(int j = 0;j<width;j++)
			visited[i][j] = false;
	visited[sy][sx] = true;
	queue<pair<int,point> > q;q.push(mp(0,mp(sy,sx)));
	while(1)
	{
		pair<int,point> a = q.front();q.pop();
		int d=a.first,x=a.second.second,y=a.second.first;
		if(x==ex&&y==ey)
		{
			return d;
		}
		for(int i = 0;i<4;i++)
		{
			 int xx=x+dx[i],yy=y+dy[i];
            if(0<=xx && xx<width && 0<=yy && yy<height && maze[yy][xx]!='X' && !visited[yy][xx]){
                visited[yy][xx]=true;
                q.push(mp(d+1,mp(yy,xx)));
            }
		}
	}
}

int main()
{
	int cx[10],cy[10],n;
	//freopen("I:\\0558-in2.txt","r",stdin);
	scanf("%d%d%d",&height,&width,&n);
	//&#36755;入迷&#23467; 
	for(int i = 0;i<height;i++)
	{
		scanf("%s",maze[i]);
		//&#26597;找老鼠&#24034;的位置
		for(int j = 0;j<width;j++)
		{
			if(maze[i][j]=='S')
			{
				cy[0] = i;
				cx[0] = j;
			}
			else if(isdigit(maze[i][j]))
			{
				int k = maze[i][j]-'0';
				cx[k] = j;cy[k] = i;
			}
			
		}
	}
	int cost = 0;
	
	for(int i = 0;i<n;i++)
		cost += shortDistance(cx[i],cy[i],cx[i+1],cy[i+1]);
	printf("%d\n",cost);
	return 0;
}

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

using namespace std;

#define ALL(co) co.begin(), co.end()
#define tpl(...) make_tuple(__VA_ARGS__)

typedef long long LL;
typedef pair<int, int> P; typedef pair<int, P> IP; typedef pair<P, P> PP;
typedef vector<int> Array; typedef vector<vector<int> > Array2;
typedef vector<LL> LArray; typedef vector<P> PArray; typedef vector<string> SArray;

const int INF = 1 << 29;
const LL LINF = 1LL << 60;

inline int getInt() { int itiv; return (cin >> itiv, itiv); }
template <typename T> void readAll(vector<T>& vec) { for (int i = 0, size = vec.size(); i < size; i++) cin >> vec[i]; }
template <typename T, typename U> void readAll(vector<pair<T, U> >& vec) { for (int i = 0, size = vec.size(); i < size; i++) cin >> vec[i].first >> vec[i].second; }
template < typename T > inline string toString( const T &a ){ ostringstream oss; oss << a; return oss.str(); };
inline bool between(int min, int max, int n) { return min <= n && n <= max; }
inline bool inRange(int begin, int end, int n) { return begin <= n && n < end; }
inline bool inRange(int size, int n) { return 0 <= n && n < size; }

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


int main(void)
{
	ios::sync_with_stdio(false);
	int h, w, n;
	while(cin >> h >> w >> n && n)
	{
		SArray stage(h);
		PArray cheese(n + 1);
		for (int i = 0; i < h; i++)
		{
			cin >> stage[i];
			for (int j = 0; j < w; j++)
			{
				char c = stage[i][j];
				if(c == 'S')
				{
					cheese[0] = P(i, j);
				}
				if(inRange(10, c - '0'))
				{
					cheese[c - '0'] = P(i, j);
				}
			}
		}

		int ans = 0;
		vector<vector<bool>> visited(h, vector<bool>(w));
		for (int i = 0; i < n; i++)
		{
			P start = cheese[i];
			P goal = cheese[i + 1];

			for (int i = 0; i < h; i++)
			{
				for (int j = 0; j < w; j++)
				{
					visited[i][j] = false;
				}
			}
			queue<IP> que;
			que.push(IP(0, start));
			while (!que.empty())
			{
				IP ip = que.front(); que.pop();
				P p = ip.second;
				visited[p.first][p.second] = true;

				if(p == goal)
				{
					ans += ip.first;
					break;
				}

				for (int j = 0; j < 4; j++)
				{
					int nr = p.first + dr[j], nc = p.second + dc[j];
					if(!inRange(h, nr) || !inRange(w, nc) || stage[nr][nc] == 'X' || visited[nr][nc]) continue;
					visited[p.first][p.second] = true;
					que.push(IP(ip.first + 1, P(nr, nc)));
				}
			}
		}

		cout << ans << endl;
	}
	return 0;
}