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<string>
#include<queue>
#define MAX 1002
using namespace std;

char xy[MAX][MAX];
int cost[MAX][MAX];
int hp[MAX][MAX];

const int INF=1>>21;

struct state{
  int x;
  int y;
  int co;
  int hp;
  state(){}
  state(int x,int y,int co,int hp):
    x(x),y(y),co(co),hp(hp){}
};

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

int H,W,N;

int solve(int x,int y){
  int i,j;
  queue<state> q;
  q.push( state(x,y,0,1) );
  cost[x][y]=0;
  hp[x][y]=1;

  while( !(q.empty()) ){

    state p = q.front();
    q.pop();

    x=p.x;
    y=p.y;

    int hpf=0;

    for(i=0;i<4;i++){

      if( x+dx[i] < 0 || x+dx[i] >= W || y+dy[i] < 0 || y+dy[i] >= H )
	continue;

      if(xy[y+dy[i]][x+dx[i]]=='X') continue;

      if(cost[x+dx[i]][y+dy[i]]<p.co+1){
	if(hp[x+dx[i]][y+dy[i]]==p.hp){
	  continue;
	}
      }
      
      if(xy[y+dy[i]][x+dx[i]]-'0' == p.hp){
	hpf=1;
	
	if(p.hp >= N){
	  return p.co+1;
	}
	
	while( !(q.empty()) ){
	  q.pop();
	}
	
	q.push( state(x+dx[i],y+dy[i],p.co+1,p.hp+hpf) );
	
	break;
	
      }
      
      cost[x][y]=p.co;
      hp[x][y]=p.hp;

      q.push( state(x+dx[i],y+dy[i],p.co+1,p.hp) );


    }

  }

  return -1;
}

main(){
  int i,j,sx,sy;

  cin >> H >> W >> N;

  for(i=0;i<H;i++){
    scanf("%s",xy[i]);
    for(j=0;j<W;j++){
      if(xy[i][j]=='S'){
	sx=j;
	sy=i;
      }
    }
  }

  int n=solve(sx,sy);

  cout << n << endl; 
  
  return 0;
}

C++: #include<iostream>
#include<cmath>
#include <queue>
#include <cstdio>
using namespace std;

int sx,sy;
int dx[4]={1,0,-1,0};
int dy[4]={0,1,0,-1};
int use[1000][1000];
char  state[1000][1000];
int H,W,N;
queue<pair<int,int> > quer;
bool check(int nowx,int nowy){
  return nowx>=0 && nowy>=0 && nowy<H && nowx<W  && use[nowx][nowy]==0 && state[nowx][nowy]!='X';
}
void solve(int nx,int ny)
{

  for(int i=0;i<4;i++){
    if(check(nx+dx[i],ny+dy[i]) && !( nx+dx[i]==sx && ny+dy[i]==sy)){
      quer.push( pair<int, int >(nx+dx[i],ny+dy[i]) );
      use[nx+dx[i]][ny+dy[i]]=use[nx][ny]+1;
    }
    }
  
}
int achieve(int goalNumber){

  solve(sx,sy);
  while(state[quer.front().first][quer.front().second]!=goalNumber+'0'){
    solve(quer.front().first,quer.front().second);

    quer.pop();
  }
  sx=quer.front().first;
  sy=quer.front().second;
  // cout << sx << sy << endl;
  while(!quer.empty()){
    quer.pop();
  }
  /* for(int i=0;i<H;i++){
    for(int j=0;j<W;j++){
      //cout << use[j][i] ;
      printf("%3d",use[j][i]);
    }
    cout << endl;
    }*/
  // cout << endl;
  return  use[sx][sy];
  //
}

int main(void){

  int sum=0;
  cin >> H >> W >> N;
  for(int i=0;i<H;i++){
    for(int j=0;j<W;j++){
      cin >> state[j][i];
      if(state[j][i] == 'S'){
	sx=j;
	sy=i;
      }
	
    }
  }
  for(int l=1;l<=N;l++){
   
    for(int i=0;i<H;i++){
      for(int j=0;j<W;j++){
	use[j][i]= 0;
      }
    }
  
    sum+=achieve(l);
  }
  cout << sum << endl;
}

C++: #include<bits/stdc++.h>
#include<ctype.h>
#define int long long int
#define rep(a,b) for(int a=0;a<b;a++)
#define INF 1000006
using namespace std;

int tx[] = {1,0,-1,0};
int ty[] = {0,1,0,-1};
int w,h,che,sx,sy;
char bases;
int base[1003][1003],base2[1003][1003],memo[1003][1003];

int chee(int x,int y,int n){
    int ans=INF;
    if(memo[x][y]>0&&memo[x][y]!=INF)return memo[x][y];
    else if(base[x][y]==n)return 0;
    else if(base[x][y]>=0){
        base[x][y]=-1;
        for(int i=0;i<4;i++){
            if(x+tx[i]>=0&&x+tx[i]<w&&y+ty[i]>=0&&y+ty[i]<h){
                ans = min(ans,chee(x+tx[i],y+ty[i],n)+1);
            }
        }base[x][y]=0;
    }
    memo[x][y]=ans;
    return ans;
}
void sho(int b[1003][1003],int a[1003][1003]){
    rep(i,1003){
        rep(j,1003){
            b[i][j]=a[i][j];
        }
    }
}

signed main(){
    int zx[20],zy[20];
    cin >> h >> w >> che;
    rep(f,h){
        rep(s,w){
            cin >> bases;
            switch(bases){
                case 'S':sx=s;sy=f;
                case '.':base[s][f]=0;
                break;
                case 'X':base[s][f]=-1;
                break;
                default:{base[s][f]=bases - '0';
                        zx[base[s][f]]=s;
                        zy[base[s][f]]=f;
                        }

            }
        }
    }
    sho(base2,base);
    int ans=0;
    ans+=chee(sx,sy,1);
    for(int i=2;i<=che;i++){
        sho(base,base2);
        fill((int*)memo,(int*)(memo+1003),0);
        ans+=chee(zx[i-1],zy[i-1],i);
    }
    cout << ans << endl;
return 0;
}

C++: #include <iostream>
#include <cstring>
#include <queue>
#include <utility>
#define MAXHW 1000 + 1

using namespace std;
typedef pair<int, int> P;

int n, m, H, W, N, d[MAXHW][MAXHW];
char fac[MAXHW][MAXHW];

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

int bfs(int a, int b, int s){
	memset(d, -1, sizeof(d));
	queue<P> q;
	d[a][b] = 0;
	q.push(P(a, b));
	
	while(!q.empty()){
		P p = q.front();
		q.pop();
		
		if(fac[p.first][p.second] == char(s + '0')){
			n = p.first, m = p.second;
			cout << d[p.first][p.second] << endl;
			return d[p.first][p.second];
		}
		
		for(int i = 0; i < 4; i++){
			int h = p.first + dy[i];
			int k = p.second + dx[i];
			if(h >= 0 && h < H && k >= 0 && k < W && fac[h][k] != 'X' && d[h][k] == -1){
				d[h][k] = d[p.first][p.second] + 1;
				q.push(P(h, k));
			}
		}
	}
}

int main(){
	int sum = 0;
	scanf("%d %d %d", &H, &W, &N);
	for(int i = 0; i < H; i++){
		for(int j = 0; j < W; j++){
			cin >> fac[i][j];
			if(fac[i][j] == 'S')
				n = i, m = j;
		}
	}
	for(int i = 1; i <= N; i++)
		sum += bfs(n, m, i);
	
	cout << sum << endl;
	return 0;
}