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<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<stack>
#include<queue>
#include<vector>
#include<algorithm>
#include<string>
#include<iostream>
#include<set>
#include<map>

using namespace std;
typedef long long ll;
int mod(ll a){
    int c=a%1000000007;
    if(c>=0)return c;
    else return c+1000000007;
}
typedef pair<int,int> i_i;
typedef pair<ll,ll> l_l;
#define inf 100000000/*10^8*/

/////////////////////////////////


struct ball{
    int i,j,count;
};
int h,w,n;
char room[1005][1005];
i_i goal[11];
bool done[1001][1001];

int di[4]={1,0,-1,0};
int dj[4]={0,1,0,-1};

int  dfs(int k){
    for(int i=0;i<=h-1;i++)for(int j=0;j<=w-1;j++)done[i][j]=false;
    int si=goal[k].first,sj=goal[k].second;
    int gi=goal[k+1].first,gj=goal[k+1].second;
    queue<ball> q;
    ball ba;ba.i=si;ba.j=sj;ba.count=1;
    q.push(ba);
    bool whi=true;
    int ans=0;
    while(whi){
        ball pos=q.front();q.pop();
        done[pos.i][pos.j]=true;
        for(int i=0;i<=3;i++){
            int ii=pos.i+di[i],jj=pos.j+dj[i];
            if(0<=ii&&ii<=h-1&&0<=jj&&jj<=w-1&&room[ii][jj]!='X'&&done[ii][jj]==false){
                if(ii==gi&&jj==gj)ans=pos.count,whi=false;
                else{
                    ba.i=ii;ba.j=jj;ba.count=pos.count+1;
                    q.push(ba);
                }
            }
        }
    }
    return ans;
}
int main(){
    cin>>h>>w>>n;
    for(int i=0;i<=h-1;i++){
        scanf("%s",room[i]);
        for(int j=0;j<=w-1;j++){
            if(room[i][j]=='.');
            else if(room[i][j]=='X');
            else if(room[i][j]=='S')goal[0]=make_pair(i,j);
            else goal[room[i][j]-'0']=make_pair(i,j);
        }
    }
    int ans=0;
    for(int i=0;i<=n-1;i++){
        ans+=dfs(i);
    }
    
    cout<<ans<<endl;
    return 0;
}

C++: #include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <array>
#include <queue>
#include <algorithm>
#include <utility>
#include <cmath>
#include <map>
#include <set>

#define INF_LL 9000000000000000000
#define INF 2000000000

#define REP(i, n) for(int i = 0;i < (n);i++)
#define FOR(i, a, b) for(int i = (a);i < (b);i++)

using namespace std;

typedef long long ll;
typedef pair<int, int> PII;

class Union_find{
private:
	vector<int> par;
	vector<int> rank;
	int n;

public:
	Union_find(int a){
		n = a;
		for(int i = 0;i < n;i++){
			par.push_back(i);
			rank.push_back(0);
		}
	}

	int find(int x){
		if(par[x] == x){
			return x;
		}else{
			return par[x] = find(par[x]);
		}
	}

	void unite(int x, int y){
		x = find(x);
		y = find(y);
		if(x == y) return;

		if(rank[x] < rank[y]){
			par[x] = y;
		}else{
			par[y] = x;
			if(rank[x] == rank[y]) rank[x]++;
		}
	}

	bool same(int x, int y){
		return find(x) == find(y);
	}
};

int chain[10002];

int no(int idx){
	int c = 1;
	int p = idx - 1;
	int q = idx + 1;
	int res = 0;
	while(chain[p] == chain[idx]){
		p--;
		c++;
	}
	while(chain[q] == chain[idx]){
		q++;
		c++;
	}
	while(c >= 4){
		res += c;
		c = 0;
		if(chain[q] != chain[p]) return res;
		if(chain[q] == chain[p] && chain[p] == -1) return res;

		int org = chain[p];
		while(chain[p] == org){
			p--;
			c++;
		}
		while(chain[q] == org){
			q++;
			c++;
		}
	}
	return res;
}

int main(void){
	int H, W, N;
	int target = 1;
	int res = 0;
	int sx, sy;
	queue<PII> que;
	cin >> H >> W >> N;
	string field[1002];
	field[0] = string(1002, 'X');
	field[H+1] = string(1002, 'X');
	REP(i, H){
		cin >> field[i+1];
		field[i+1] = 'X' + field[i+1] + 'X';
		if(field[i+1].find('S') != -1){
			que.push(PII(field[i+1].find('S'), i+1));
			sx = que.front().first;
			sy = que.front().second;
		}
	}

	while(target <= N){
		int take[1002][1002];
		REP(i, 1002){
			fill(take[i], take[i]+1002, INF);
		}
		take[que.front().first][que.front().second] = 0;
		while(!que.empty()){
			PII p = que.front(); que.pop();
			int dx[4] = {-1, 0, 0, 1};
			int dy[4] = {0, -1, 1, 0};
			REP(i, 4){
				int x = p.first + dx[i];
				int y = p.second + dy[i];
				if(field[y][x] == 'X') continue;
				if(take[x][y] != INF) continue;
				else{
					if(field[y].substr(x, 1) == to_string(target)){
						res += take[p.first][p.second]+1;
						queue<PII>().swap(que);
						sx = x;
						sy = y;
						target++;
						break;
					}else{
						take[x][y] = min(take[x][y], take[p.first][p.second] + 1);
						que.push(PII(x, y));
					}
				}
			}
		}
		que.push(PII(sx, sy));
	}
	cout << res << endl;
}

C++: #include <iostream>
#include <queue>
#include <vector>
#define MAX 1000

using namespace std;

const int INF = 1000000;

typedef pair<int,int> P;

int n,m;
char cheese[MAX+1][MAX+1];
 
int bfs(int sy,int sx,int gy,int gx){
    
  int dx[4]={1,0,-1,0};
  int dy[4]={0,1,0,-1};
  int d[MAX][MAX];
  queue<P> q;
     
    for( int i = 0 ; i < n ; i++ )
        for( int j = 0 ; j < m ; j++ )
            d[i][j] = INF;
     
    q.push( P(sy , sx) );
    d[sy][sx] = 0;
     
    while( q.size() ){
        P p = q.front(); 
	q.pop();

        if(p.first == gy && p.second == gx) break;
	
        for(int i = 0 ; i < 4 ; i++){
	  int x = p.first + dx[i];
	  int y = p.second + dy[i];
          
	  if( 0 <= x && x < n &&
	      0 <= y && y < m &&
	      d[x][y] == INF &&
	      mp[nx][ny]!='X'){
	    q.push( P(nx , ny) );
	    d[x][y] = d[p.first][p.second] + 1;
	  }
        }
    }
    
    return d[gy][gx];
}

int main(void){

    int num;
 
    cin >> n >> m >> num;
    vector<P> v(num + 1);
     
    for( int i = 0 ; i < n ; i++ ){
        for( int j = 0 ; j < m ; j++ ){
            cin >> cheese[i][j];
            if( cheese[i][j]=='S'){
                v[0].first = i;
                v[0].second = j;
            }
            if('1' <= cheese[i][j] && cheese[i][j] <= '9'){
                v[mp[i][j]-'0'].first = i;
                v[mp[i][j]-'0'].second = j;
            }
        }
    }
     
    int sum = 0;
    for(int i = 1 ; i < num+1 ; i++){
        sum += bfs(v[i-1].first,v[i-1].second,v[i].first,v[i].second);
    }
    cout << sum << endl;
     
    return 0;
}