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<iostream>
#include<cstdio>
#include<queue>

using namespace std;

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

struct P{
    int x;
    int y;
};

int w,h,n;
char feld[1100][1100];
int d[1100][1100];
int sx,sy,gx,gy;
int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};
int ans=0;
P che[15];


int bfs(){
    REP(i,n){
        P sp=che[i];
        sx=che[i].x;
        sy=che[i].y;
        gx=che[i+1].x;
        gy=che[i+1].y;
        queue<P> que;
        REP(y,h)REP(x,w)d[y][x]=INF;
        que.push(sp);
        d[sy][sx]=0;
        while(!que.empty()){
            P p=que.front();
            que.pop();
            int x=p.x;
            int y=p.y;
            if(x==gx&&y==gy){
                ans+=d[gy][gx];
                break;
            }
            REP(i,4){
                int nx=x+dx[i];
                int ny=y+dy[i];
                if(nx<0||ny<0&&nx>=w&&ny>=h)continue;
                if(feld[ny][nx]!='X'&&d[ny][nx]==INF){
                    P next;
                    next.x=nx;
                    next.y=ny;
                    que.push(next);
                    d[ny][nx]=d[y][x]+1;
                }
            }
        }
    }
    return 0;
}

int main(){
    cin>>h>>w>>n;
    REP(y,h){
        REP(x,w){
            scanf(" %c",&feld[y][x]);
            if(feld[y][x]=='S'){
                che[0].x=x;
                che[0].y=y;
            }else if(feld[y][x]>='1'&&feld[y][x]<='9'){
                char c=feld[y][x];
                che[c-'0'].x=x;
                che[c-'0'].y=y;
            }
        }
    }
    bfs();
    cout<<ans<<endl;
    return 0;
}

C++: #include <sstream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <iostream>
#include <utility>
#include <set>
#include <cctype>
#include <queue>
#include <stack>
#include <cstdio>
#include <cstdlib>
#include <cmath>
using namespace std;
#define MAXH 1010
#define MAXW 1010
#define MAXN 11
#define INF 10000000
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
int H, W, N;
char field[MAXH][MAXW];
pair<int, int> goal[MAXN];
int main(void) {
    cin >> H >> W >> N;
    for (int i = 0; i < H; i++)
        for (int j = 0; j < W; j++)
            cin >> field[i][j];
    for (int i = 0; i < H; i++) {
        for (int j = 0; j < W; j++) {
            int x = field[i][j] - '0';
            if (1 <= x && x <= N) {
                goal[x] = make_pair(i, j);
            } else if (field[i][j] == 'S') {
                goal[0] = make_pair(i, j);
            }
        }
    }
    int ret = 0;
    for (int a = 0; a < N; a++) {
        int d[H][W];
        for (int i = 0; i < H; i++)
            for (int j = 0; j < W; j++)
                d[i][j] = INF;
        queue<int> X;
        queue<int> Y;
        X.push(goal[a].second); Y.push(goal[a].first);
        d[goal[a].first][goal[a].second] = 0;
        while (!X.empty()) {
            int x = X.front(); X.pop();
            int y = Y.front(); Y.pop();
            if (x == goal[a+1].second && y == goal[a+1].first) {
                ret += d[y][x];
                break;
            }
            for (int i = 0; i < 4; i++) {
                int nx = x + dx[i];
                int ny = y + dy[i];
                if (0 <= nx && nx < W && 0 <= ny && ny < H && d[ny][nx] == INF && field[ny][nx] != 'X') {
                    d[ny][nx] = d[y][x] + 1;
                    X.push(nx);
                    Y.push(ny);
                }
            }
        }
    }
    cout << ret << endl;
    return 0;
}

C++: #include <bits/stdc++.h>
using namespace std;

#define rep(i,s,n) for (int i = (int)s; i < (int)n; i++)
#define ll long long
#define pb push_back
#define eb emplace_back
#define All(x) x.begin(), x.end()
#define Range(x, i, j) x.begin() + i, x.begin() + j
#define lbidx(x, y) lower_bound(x.begin(), x.end(), y) - x.begin()
#define ubidx(x, y) upper_bound(x.begin(), x.end(), y) - x.begin()
#define llbidx(x, y, z) lower_bound(x.begin(), x.end(), z) - lower_bound(x.begin(), x.end(), y) // 二要素間の距離
#define deg2rad(deg) ((((double)deg)/((double)360)*2*M_PI))
#define rad2deg(rad) ((((double)rad)/(double)2/M_PI)*(double)360)
#define Find(set, element) set.find(element) != set.end()

typedef pair<int, int> PI;
typedef pair<ll, ll> PLL;

template<class T>
inline bool chmax(T &a, T b) {
  if(a < b) {
    a = b;
    return true;
  }
  return false;
};

template<class T>
inline bool chmin(T &a, T b) {
  if(a > b) {
    a = b;
    return true;
  }
  return false;
};

static const int INF = 1e9+7;

int grid[1005][1005];
vector<vector<bool>> visited(1005, vector<bool> (1005, false));
vector<int> dis(1005 * 1005, INF);
int H, W, N;
int dx[4] = { 0, 1, 0, -1 }; // N, E, S, W
int dy[4] = { -1, 0, 1, 0 }; // N, E, S, W

int bfs(int s, int e) {
  // visited, dis 初期化
  rep(i, 0, H) {
    rep(j, 0, W) {
      visited[i][j] = false;
      dis[i * W + j] = INF;
    }
  }

  queue<int> q;
  q.push(s);
  dis[s] = 0;
  while (!q.empty()) {
    int u = q.front(); q.pop();
    int uy = u / W;
    int ux = u % W;
    if (visited[uy][ux]) continue;
    if (u == e) {
      break;
    }
    visited[uy][ux] = true;
    rep(i, 0, 4) {
      int vy = u / W + dy[i];
      int vx = u % W + dx[i];
      int v = vy * W + vx;
      if (0 <= vx && vx < W && 0 <= vy && vy < H) {
        if (grid[vy][vx] != -1 && !visited[vy][vx]) {
          q.push(v);
          dis[v] = min(dis[v], dis[u] + 1);
        }
      }
    }
  }

  return dis[e];
};

int main() {
  cin >> H >> W >> N;
  vector<int> points(N+1, 0);

  char ch;
  int s;
  rep(i, 0, H) {
    rep(j, 0, W) {
      cin >> ch;
      if (ch == 'S') {
        s = i * W + j;
        grid[i][j] = 0;
        points[0] = i * W + j;
      } else if (ch == 'X') {
        grid[i][j] = -1;
      } else if (ch == '.') {
        grid[i][j] = 0;
      } else {
        grid[i][j] = (int) ch - 48;
        points[grid[i][j]] = i * W + j;
      }
    }
  }

  int ans = 0;
  rep(i, 0, N) {
    ans += bfs(points[i], points[i+1]);
  }
  cout << ans << endl;
};