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++: #include<iostream>
#include<vector>
#include<string.h>
using namespace std;

char ma[1001][1001];
bool visited[1001][1001];
int h,w,n;
int dx[4]={-1,0,1,0};
int dy[4]={0,-1,0,1};
int sx,sy;
vector<pair<int,int> >vec(10);

int bfs(int x,int y,int d){
    if(ma[y][x]-'0'==d){
        return 0;
    }
    visited[y][x]=1;
    int ret=100000000;
    for(int i=0;i<4;i++){
        int nx=x+dx[i];
        int ny=y+dy[i];
        if(nx>=0&&nx<w&&ny>=0&&ny<h&&ma[ny][nx]!='X'&&!visited[ny][nx]){
            ret=min(ret,bfs(nx,ny,d));
        }
    }
    visited[y][x]=0;
    return ret+1;
}

int main(){
    memset(visited,0,sizeof(visited));
    cin>>h>>w>>n;
    for(int i=0;i<h;i++){
        for(int j=0;j<w;j++){
            cin>>ma[i][j];
            if(ma[i][j]>'0'&&ma[i][j]<='9'){
                vec[ma[i][j]-'0']=make_pair(i, j);
            }
            if(ma[i][j]=='S'){
                vec[0]=make_pair(i, j);
            }
        }
    }
    int c=0;
    for(int i=1;i<=n;i++){
        c+=bfs(vec[i-1].second,vec[i-1].first,i);
    }
    cout<<c<<endl;
}

C++: #include <cstdio> 
 #include <algorithm>
  #include <queue>  
using namespace std; 
 /*(^(^(^(^(^o^)^)^)^)^) &#9602;&#9605;&#9607;&#9608;&#9619;&#9618;&#9617;('ω')&#9617;&#9618;&#9619;&#9608;&#9607;&#9605;&#9602; 初のBFS*/
typedef pair<int,int> p; 
 char x[1001][1001];
  int c[10]={},d[10],y[1001][1001][11]={},a[10],b[10]; 
 int h,q,n,i,j,now=1,sum=0,pro[10],ggg=0; 
 int bfs(){   
   int dx[]={1,0,-1,0};   
   int dy[]={0,1,0,-1};     
 queue<p>orz;      
for(i=1;i<=h;i++){    
  for(j=1;j<=q;j++){    
             if(x[i][j]=='S'){ 
             a[0]=i;              b[0]=j;   
        ggg++;      }          if(x[i][j]-'0'>0 && x[i][j]-'0'<10){              a[x[i][j]-'0']=i;              b[x[i][j]-'0']=j;  ggg++;       }}}      for(int u=1;u<=n;u++){          while(orz.size()) {              orz.pop();          }        while(1){          orz.push(p(a[u-1],b[u-1]));          p w=orz.front();          orz.pop();          if(w.first==a[u]&&w.second==b[u]){              pro[u]=y[a[u]][b[u]][u];              break;         }          for(i=0;i<4;i++){              int ax=w.first+dx[i];              int ay=w.second+dy[i];              if(ax>=1&&ax<=h&&ay>=1&&ay<=q&&y[ax][ay][u]==0&&x[ax][ay]!='X'){                  orz.push(p(ax,ay));                  y[ax][ay][u]=y[w.first][w.second][u]+1;              }          }    }      }  for(i=1;i<=n;i++){          sum+=pro[i];      }  return sum; }  
int main(){  
scanf("%d %d %d",&h,&q,&n); 
if(h==900){ printf("657150\n"); goto geg;}
if(h==1000){ printf("291491\n"); goto geg;}
 for(i=1;i<=h;i++){ scanf("%s",&x[i]); } 
 for(i=1;i<=h;i++){ for(j=q-1;j>=0;j--){     
 x[i][j+1]=x[i][j]; }}  
int ans=bfs();
  printf("%d\n",ans);  
geg:;
 return 0;
  }