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 <vector>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <deque>
#include <algorithm>
#include <utility>
#include <functional>
#include <sstream>
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <ctime>
#include <climits>

using namespace std;

inline int toInt(string s) { int v; istringstream sin(s); sin >> v; return v;}
template<class T> inline string toString(T x) { ostringstream sout; sout << x; return sout.str();}

typedef vector<int> vi;
typedef vector<vi>  vvi;
typedef vector<string> vs;
typedef pair<int, int> pii;
typedef long long ll;

#define ALL(a) (a).begin(),(a).end()
#define RALL(a) (a).rbegin(),(a).rend()
#define EACH(t,i,c) for(t::iretator i=(c).begin(); i!=(c).end(); ++i)
#define EXIST(s,e) ((s).find(e)!=(s).end())
#define FOR(i,a,b) for(int i=(a);i<=(b);++i)
#define REP(i,n) FOR(i,0,n-1)

const double EPS = 1e-10;

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

vvi field(1002, vi(1002, 0));
vvi cost(1002, vi(1002, 0));

int bfs(pii start, pii goal) {
	REP(i, 1002) {
		REP(j, 1002) {
			cost[i][j] = 10000;
		}
	}
	cost[start.first][start.second] = 0;

	queue<pii> Q;
	Q.push(start);

	while(!Q.empty()) {
		pii p = Q.front();
		Q.pop();
		if(p == goal) {
			break;
		}
		REP(i, 4) {
			int ny = p.first + dy[i], nx = p.second + dx[i];
			if(field[ny][nx] && cost[ny][nx]==10000) {
				Q.push(pii(ny, nx));
				cost[ny][nx] = cost[p.first][p.second]+1;
			}
		}
	}

	return cost[goal.first][goal.second];
}

int main() {
	int H, W, N;
	cin >> H >> W >> N;

	vector<pii> point(N+1);

	string str;
	REP(i, H) {
		cin >> str;
		REP(j, W) {
			switch(str[j]) {
			case 'S':
				point[0].first = i+1;
				point[0].second = j+1;
				field[i+1][j+1] = 1;
				break;
			case '1': case '2': case '3': case '4': case '5':
			case '6': case '7': case '8': case '9':
				point[str[j]-'0'].first = i+1;
				point[str[j]-'0'].second = j+1;
				field[i+1][j+1] = 1;
				break;
			case 'X':
				field[i+1][j+1] = 0;
				break;
			case '.':
				field[i+1][j+1] = 1;
				break;
			}
		}
	}

	int ans = 0;
	REP(i, N) {
		ans += bfs(point[i], point[i+1]);
	}

	cout << ans << endl;
	return 0;
}

C++: #include <iostream>
#include <queue>
using namespace std;
#define MAX_H 1000
#define MAX_W 1000
#define INF 100000000

typedef pair<int, int> P;

char a[MAX_H][MAX_W];
int d[MAX_H][MAX_W];
int h, w, n;
int sx, sy;
int gx, gy;

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

int bfs() {
  int count = 0;
  for (int k = 1; k <= n; k++) {
    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[sy][sx] = 0;

    while (!que.empty()) {
      P p = que.front();
      que.pop();
      if (p.first == gx && p.second == gy) {
	count += d[p.second][p.first];
	break;
      }

      for (int i = 0; i < 4; i++) {
	int nx = p.first + dx[i], ny = p.second + dy[i];
	if (0 <= nx && nx < w && 0 <= ny && ny < h && a[ny][nx] != 'X' &&
	    d[ny][nx] == INF) {
	  que.push(P(nx, ny));
	  d[ny][nx] = d[p.second][p.first] + 1;
	}
      }
    }
    sx = gx;
    sy = gy;
    for (int i = 0; i < h; i++) {
      for (int j = 0; j < w; j++) {
	if (a[i][j] == k + 1 + '0') {
	  gx = j;
	  gy = i;
	}
      }
    }
  }
  return count;
}

int main() {
  cin >> h >> w >> n;
  for (int i = 0; i < h; i++)
    for (int j = 0; j < w; j++)
      cin >> a[i][j];

  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      if (a[i][j] == 'S') {
	sx = j;
	sy = i;
      } else if (a[i][j] == '1') {
	gx = j;
	gy = i;
      }
    }
  }

  int ans = bfs();
  cout << ans << endl;

  return 0;
}

C++: 
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<deque>

using namespace std;

typedef pair<int,int>P;

const int maxn=1e3+5;
int inf=500;

int h,w,n,sx,sy,goal[10],book[maxn][maxn],Next[4][2]={{0,1},{1,0},{-1,0},{0,-1}};
char s[maxn][maxn];

int judge(int row,int col)
{
    if(row>=0&&row<h&&col>=0&&col<w){
        return 1;
    }
    return 0;
}

int bfs()
{
    int res=0;
    deque<P>q;
    for(int ci=0;ci<n;ci++){
        fill(book[0],book[0]+maxn*maxn,inf);
        q.push_back(P(sx,sy));
        book[sx][sy]=0;
        while(!q.empty()){
            int x=q.front().first;
            int y=q.front().second;
            q.pop_front();
            if((int)s[x][y]==49+ci){
                goal[ci]=book[x][y];
                sx=x;
                sy=y;
                break;
            }
            for(int i=0;i<4;i++){
                int nx=x+Next[i][0];
                int ny=y+Next[i][1];
                if(judge(nx,ny)&&s[nx][ny]!='X'&&book[nx][ny]==inf){
                    q.push_back(P(nx,ny));
                    book[nx][ny]=book[x][y]+1;
                }
            }
        }
        q.clear();
        res+=goal[ci];
    }
    return res;
}

int main()
{
    cin>>h>>w>>n;
    for(int i=0;i<h;i++){
        for(int j=0;j<w;j++){
            cin>>s[i][j];
            if(s[i][j]=='S'){
                sx=i;
                sy=j;
            }
        }
    }
  //  cout<<sx<<" "<<sy<<endl;
    int res=bfs();
    cout<<res<<endl;
    return 0;
}