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;

typedef struct xyt{
	int xx;
	int yy;
	int tt;
}xyt;

int H, W, N, minute = 0;
char area[1001][1001] = {};
bool areab[1001][1001] = {};
int dx[4] = {0,1,0,-1};
int dy[4] = {1,0,-1,0};


void dfs(int x, int y){
	int X, Y, time ;
	int HP =1;
	xyt now = {x, y, 0};
	queue <xyt> Q;
	Q.push (now);

	while(HP <= N){
		X = Q.front().xx;
		Y = Q.front().yy;
		time = Q.front().tt;
		Q.pop();

		for(int i = 0; i <= 4 ;i++){
			if(X + dx[i] <= 0 || Y + dy[i] <= 0 || X + dx[i] > W || Y + dy[i] > H)continue;

			if(areab[X + dx[i]][Y + dy[i]] == 0){
				if(area[X + dx[i]][Y + dy[i]] == HP){
					minute += time;
					while(!Q.empty()){
						Q.pop();
					}
					now.xx = X + dx[i];
					now.yy = Y + dy[i];
					now.tt = 0;
					Q.push (now);
					HP++;
					break;
				}else{
					now.xx = X + dx[i];
					now.yy = Y + dy[i];
					now.tt = time + 1;
					Q.push (now);
				}
			}
		}
	}
	return;
}


int main(){
	cin >> H >> W >> N;
	for(int i = 1; i <= H ;i++){
		for(int j = 1; j <= W ;j++){
			cin >> area[j][i];
			if(area[j][i] == 'X'){
				areab[j][i] = 1;
			}
		}
	}
	for(int i = 1; i <= H ;i++){
		for(int  j = 1; j <= W ;j++){
			if(area[j][i] == 'S'){
				dfs(j, i);
			}
		}
	}
	cout << minute << endl;
	return 0;
}

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

using namespace std;

const int MAX_W = 1005, MAX_H = 1005;
const int inf = 1e+9;

int w, h, C;
char G[MAX_H][MAX_W];
int sx, sy, ex, ey;
int dx[4] = {0, 1, 0, -1};
int dy[4] = {1, 0, -1, 0};
struct P{int x,y;};
int d[MAX_H][MAX_W];

int bfs(char e){
    for(int i = 0;i < h;i++){
        for(int j = 0;j < w;j++){
            d[i][j] = inf;
        }
    }
    queue<P> que;
    que.push((P){sx, sy});
    d[sx][sy] = 0;
    while(!que.empty()){
        P p = que.front();que.pop();

        if(G[p.x][p.y] == e) {
            ex = p.x;
            ey = p.y;
            break;
        }

        for(int i = 0;i < 4;i++){
            int nx = p.x + dx[i], ny = p.y + dy[i];
            if(0<=nx && nx<h && 0<=ny && ny<w && G[nx][ny]!='X' && d[nx][ny] > d[p.x][p.y]+1){
                d[nx][ny] = d[p.x][p.y] + 1;
                que.push((P){nx, ny});
            }
        }
    }
    sx = ex;
    sy = ey;
    return d[ex][ey];
}

void solve(){
    int sum = 0;
    for(int i = 1;i <= C;i++){
        sum+=bfs(i+'0');
    }
//    for(int i = 0;i <h;i++){
//        for(int j = 0;j <w;j++){
//            cout<<d[i][j]<<' ';
//        }
//        cout<<endl;
//    }
    printf("%d\n", sum);
}

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

    for(int i = 0;i < h;i++){
        scanf("%s", G[i]);
    }

    for(int i = 0;i < h;i++){
        for(int j = 0;j < w;j++){
            if(G[i][j] == 'S'){
                sx = i;
                sy = j;
            }
        }
    }

//    for(int i = 0;i <h;i++){
//        for(int j = 0;j <w;j++){
//            cout<<G[i][j]<<' ';
//        }
//        cout<<endl;
//    }
        solve();

    return 0;
}

/*
3 3 1
S..
...
..1

4 5 2
.X..1
....X
.XX.S
.2.X.
 */

C++: //
//  0558.cpp
//  
//
//  Created by Yoshida Satoshi on 2017/11/16.
//
//

#include <iostream>
#include <queue>
#include <utility>
#include <stdlib.h>

#define MAX 1000
#define INF 100000000
#define FOR(index,max) for(int index=0;index<max;index++)

using namespace std;

typedef pair<int, int> P;

int main(){
    int dx[4]={1,-1,0,0};
    int dy[4]={0,0,1,-1};
    
    int nx,ny;
    
    queue<P> que;
    int H,W,N;
    int state[MAX][MAX];//0:????????°or????????? -1:????????¶???
    bool isVisited[MAX][MAX];
    int d[MAX][MAX];
    int ans=0;
    int sx[9];
    int sy[9];
    P p;
    char in;
    cin>>H>>W>>N;
    FOR(i,H){
        FOR(j,W){
            cin>>in;
            if(in=='S'){
                sx[0]=i;
                sy[0]=j;
                state[i][j]=0;
            }
            else if(in=='X') state[i][j]=-1;
            else if(in=='.') state[i][j]=0;
            else{
                state[i][j]=0;
                sx[in-'0']=i;
                sy[in-'0']=j;
                
            }
        }
    }
    
    FOR(k,N){
        FOR(i,H){
            FOR(j,W){
                isVisited[i][j]=false;
                d[i][j]=INF;
            }
        }
        que.push(P(sx[k],sy[k]));
        d[sx[k]][sy[k]]=0;
        while(que.size()){
            p=que.front();
            que.pop();
            
            if(p==P(sx[k+1],sy[k+1]))   break;
            
            FOR(l,4){
                nx=p.first+dx[l];
                ny=p.seond+dy[i];
                
                if(!(nx<0||ny<0||nx>H-1||ny>W-1||state[nx][ny]==-1||d[nx][ny]==INF)){
                    que.push(P(nx,ny));
                    d[nx][ny]=d[p.first][p.second]+1;
                }
            }
        }
        
        ans += d[start[k+1].first][start[k+1].second];
    }
    
    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;
const int MAX=(1<<14)-1;
mouse Q[MAX+1];
int s,num;

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)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;
  }
 
 
  Q[s+num++]=(mouse){cx,cy,0,0};
  maxch[cx][cy]=0;
 
  while(true){
    t=Q[s++&MAX];
    num--;
    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[s+num++&MAX]=(mouse){nx,ny,cost+1,nch};
    }
  }
}