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

using namespace std;

typedef pair<int, int> P;

const int INF = 100000000;
const int MAX_H = 1000;
const int MAX_W = 1000;
const int MAX_N = 9;

//&#36755;入
int H, W, N;
char maze[MAX_H][MAX_W + 1];

int sx, sy;
int d[MAX_H][MAX_W];

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

//求以(sx, sy)&#20026;起点到&#36798;目&#26631;c的最短路径&#38271;度
int bfs(char c){
	//初始化
	memset(d, -1, sizeof(d));
	d[sx][sy] = 0;
	queue<P> que;
	que.push(P(sx, sy));
	//&#23485;度&#20248;先
	while(!que.empty()){
		P p = que.front();
		que.pop();
		//已找到
		if(maze[p.first][p.second] == c){
			//重置起点
			sx = p.first;
			sy = p.second;
			break;
		}

		for(int i = 0; i < 4; i ++){
			int nx = p.first + dx[i], ny = p.second + dy[i];
			//判断是否可移&#21160;以及是否已&#32463;&#35775;&#38382;&#36807;
			if(0 <= nx && nx < H && 0 <= ny && ny < W && maze[nx][ny] != 'X' && d[nx][ny] == -1){
				que.push(P(nx, ny));
				d[nx][ny] = d[p.first][p.second] + 1;
			}
		}
	}
	return d[sx][sy];
}

void solve(){
	//找起始点
	for(int i = 0; i < H; i ++){
		for(int j = 0; j < W; j ++){
			if(maze[i][j] == 'S'){
				sx = i;
				sy = j;
				break;
			}
		}
	}
	//&#23485;度&#20248;先搜索
	int ans = 0;
	for(int i = 1; i <= N; i ++){
		ans += bfs('0' + i);
	}
	printf("%d\n", ans);
}

int main(int argc, char const *argv[]){

	while(scanf("%d %d %d", &H, &W, &N)){
		for(int i = 0; i < H; i ++){
			scanf("%s", maze[i]);
		}
		solve();
	}

	return 0;
}

C++: #include "bits/stdc++.h"
using namespace std;
#ifdef _DEBUG
#include "dump.hpp"
#else
#define dump(...)
#endif

//#define int long long
#define rep(i,a,b) for(int i=(a);i<(b);i++)
#define rrep(i,a,b) for(int i=(b)-1;i>=(a);i--)
#define all(c) begin(c),end(c)
const int INF = sizeof(int) == sizeof(long long) ? 0x3f3f3f3f3f3f3f3fLL : 0x3f3f3f3f;
const int MOD = (int)(1e9) + 7;
template<class T> bool chmax(T &a, const T &b) { if (a < b) { a = b; return true; } return false; }
template<class T> bool chmin(T &a, const T &b) { if (a > b) { a = b; return true; } return false; }

int H, W, N;
char c[1010][1010];
int dx[4] = { 1,0,-1,0 };
int dy[4] = { 0,1,0,-1 };
bool flag[1010][1010];

bool inrange(int i, int j) { return i >= 0 && i < H && j >= 0 && j < W; }

int bfs(int si, int sj, int gi, int gj) {
	using State = tuple<int, int, int>;
	queue<State> q;
	q.emplace(si, sj, 0);
	memset(flag, false, sizeof(flag));
	while (q.size()) {
		int ci, cj, cnt;
		tie(ci, cj, cnt) = q.front(); q.pop();
		if (!inrange(ci, cj))continue;
		if (ci == gi&&cj == gj)return cnt;
		if (flag[ci][cj])continue;
		flag[ci][cj] = true;
		if (c[ci][cj] == 'X')continue;
		rep(i, 0, 4) {
			int ni = ci + dy[i], nj = cj + dx[i];
			q.emplace(ni, nj, cnt + 1);
		}
	}
}

signed main() {
	cin.tie(0);
	ios::sync_with_stdio(false);
	cin >> H >> W >> N;
	vector<tuple<int, int, int>> v;
	rep(i, 0, H)rep(j, 0, W) {
		cin >> c[i][j];
		if (c[i][j] == 'S') {
			v.emplace_back(0, i, j);
		}
		else if ('1' <= c[i][j] && c[i][j] <= '9') {
			v.emplace_back(c[i][j] - '0', i, j);
		}
	}
	sort(all(v));
	int ans = 0;
	rep(i, 0, v.size() - 1) {
		int ci, cj, ni, nj;
		tie(ignore, ci, cj) = v[i];
		tie(ignore, ni, nj) = v[i + 1];
		ans += bfs(ci, cj, ni, nj);
	}
	cout << ans << endl;
	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;
 
 
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+1];
  
  rep(i,h)fread(ku[i],1,w+1,stdin);
 
 
  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});
    }
  }
}