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 <set>
#include <map>
#include <list>
#include <queue>
#include <stack>
#include <cmath>
#include <ctime>
#include <cstdio>
#include <vector>
#include <string>
#include <bitset>
#include <cctype>
#include <cstdlib>
#include <cstring>
#include <utility>
#include <numeric>
#include <complex>
#include <sstream>
#include <fstream>
#include <functional>
#include <iomanip>
#include <cassert>
#include <iostream>
#include <iterator>
#include <algorithm>
using namespace std;
typedef long long ll;
const double EPS = 1e-9;
typedef vector<int> vint;
typedef pair<int, int> pint;
#define rep(i, n) REP(i, 0, n)
#define ALL(v) v.begin(), v.end()
#define MSG(a) cout << #a << " " << a << endl;
#define REP(i, x, n) for(int i = x; i < n; i++)
#define INF 100000000
template<class T, class C> void chmax(T& a, C b) { a>b ? : a = b; }
template<class T, class C> void chmin(T& a, C b) { a<b ? : a = b; }

int h, w, n;
char c[1005][1005];
int chx[15] = { 0 }, chy[15] = { 0 }, dx[] = { 0,1,0,-1 }, dy[] = { 1,0,-1,0 }, d[1005][1005] = { 0 };
typedef pair<int, int>P;

int bfs(int sx,int sy,int gx,int gy) {
	for (int i = 0; i < 1005; i++) {
		for (int j = 0; j < 1005; j++) {
			d[i][j] = -1;
		}
	}
	queue<P>que;
	que.push(P(sx, sy));
	d[sx][sy] = 0;
	while (que.size()) {
		P p = que.front();
		que.pop();
		int nowx = p.first;
		int nowy = p.second;
		cout << nowx << " " << nowy << endl;
		if (nowx == gx&&nowy == gy) break;
		for (int i = 0; i < 4; i++) {
			int nx = nowx + dx[i];
			int ny = nowy + dy[i];
			if (d[nx][ny]==-1&&0 <= nx&&nx < h && 0 <= ny&&ny < w&&c[nx][ny]!='X') {
				d[nx][ny] = d[nowx][nowy] + 1;
				que.push(P(nx, ny));
			}
		}
	}
	return d[gx][gy];
}

int main() {
	cin >> h >> w >> n;
	for (int i = 0; i < h; i++) {
		for (int j = 0; j < w; j++) {
			cin >> c[i][j];
			if (c[i][j] == 'S') {
				chx[0] = i;
				chy[0] = j;
			}
			else if ('1' <= c[i][j] && c[i][j] <= '9') {
				int number = c[i][j] - '0';
				chx[number] = i;
				chy[number] = j;
			}
		}
	}
	int cnt = 0;
	for (int i = 0; i <= n - 1; i++) {
		cnt += bfs(chx[i], chy[i], chx[i + 1], chy[i + 1]);
	}
	cout << cnt << endl;
	return 0;
}

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

typedef pair<int, int> P;

int main(void){
    int h, w, d[1001][1001], sx, sy, sum = 0, cnt=0, n;
    char maze[1001][1001], num[9] = {'1','2','3','4','5','6','7','8','9'};
    cin >> h >> w >> n;
    for(int i=0;i<h;i++){
        for(int j=0;j<w;j++){
            d[i][j] = 0;
            cin >> maze[i][j];
            if(maze[i][j] == 'S'){
                sy = i;
                sx = j;
            }
        }
    }
    queue<P> que;
    que.push(P(sx, sy));

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

    while(que.size()){
        P p = que.front();
        que.pop();
        if(cnt == n){
            cout << sum << endl;
            return 0;
        }

        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 && maze[ny][nx] != 'X' && d[ny][nx] == 0){
                d[ny][nx] = d[p.second][p.first] + 1;
                que.push(P(nx, ny));
                // cout << nx << " " << ny << " "<< maze[ny][nx] << endl;
                if(maze[ny][nx] == num[cnt]){
                    // cout << nx << " " << ny << " "<< maze[ny][nx] << endl;
                    sum += d[ny][nx];
                    //que?????????????????????
                    while(que.size()){
                        que.pop();
                    }
                    //???????????¢????????????
                    for(int i=0;i<h;i++){
                        for(int j=0;j<w;j++){
                            d[i][j] = 0;
                        }
                    }
                    que.push(P(nx, ny));
                    cnt++;
                    break; //for????????????
                }
            }
        }
    }
    return 0;
}

C++: #include <stdio.h>
#include <memory.h>
#include <stdbool.h>

int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, -1, 0, 1};
int c[1000][1000];
int dat[1000][1000];
int cost[1000][1000];
int destination = 1;
int startposx, startposy;
int h, w, n;

struct QUEUE {
  int x, y;
};
QUEUE queue[256];
int qbegin = 0, qend = 0;

void bfsToDestination(int x, int y);
void PushQueue(int x, int y);
QUEUE PopQueue();
bool isQueueEmpty();


int main (void) {

  int i, j;

  scanf("%d%d%d", &w, &h, &n);

  for(i = 0; i < h; i++) {
    for(j = 0; j < w; j++) {
      dat[j][i] = fgetc(stdin);
      if (dat[j][i] == '\n') dat[j][i] = fgetc(stdin);
      if (dat[j][i] == 'S') {
	startposx = j; startposy = i;
	cost[j][i] = 0;
      }
    }
  }

  //for(i = 0; i < h; i++) {
  //  for(j = 0; j < w; j++) {
  //    printf("%c", dat[j][i]);
  //  }
  //  printf("\n");
  //}

  for (i = 0; i < n; i++) {
    memcpy(c, dat, sizeof(dat));
    bfsToDestination(startposx, startposy);
  }
  
  printf("%d\n", cost[startposx][startposy]);
    
  return 0;
}

void bfsToDestination(int x, int y) {

  int i;
  QUEUE ret;

  qbegin = 0; qend = 0;

  // map
  // int j;
  //printf("---map\n");
  //for(i = 0; i < h; i++) {
  //  for(j = 0; j < w; j++) {
  //    printf("%c", c[j][i]);
  //  }
  //  printf("\n");
  //}

  PushQueue(x, y);
  c[x][y] = 'X';

  while(!isQueueEmpty()) {
    ret = PopQueue();
    
    //printf("ret.x:%d ret.y:%d cost.x,y:%d\n", ret.x, ret.y, cost[ret.x][ret.y]);
    
    for (i = 0; i < 4; i++) {
      int nx = ret.x + dx[i];
      int ny = ret.y + dy[i];

      if ((nx >= 0) && (ny >= 0) && (nx < w) && (ny < h )) {
	if (c[nx][ny] != 'X') {
	  PushQueue(nx, ny);
	  cost[nx][ny] = cost[ret.x][ret.y] + 1;
	  if ((c[nx][ny] - '0') == destination) {
	    destination++;
	    startposx = nx; startposy = ny;
	    return;
	  }
	  c[nx][ny] = 'X';
	}
      }
    }
  }

}

void PushQueue(int x, int y) {
  queue[qend].x = x; queue[qend].y = y;
  qend++;
}

QUEUE PopQueue() {
  QUEUE ret;
  ret.x = queue[qbegin].x; ret.y = queue[qbegin].y;
  qbegin++;

  return ret;
}

bool isQueueEmpty() {
  if (qend == qbegin) return true;

  return false;
}