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++: //
//  main.cpp

#include <iostream>
using namespace std;
using ll = long long;
const ll MAX = 10000000000000;
int h,w,n;
bool matrix[1001][1001]={{}};
bool visited[1001][1001]={{}};
pair<int,int> target;

ll min(ll x,ll y){
	if(x < y){
		return x;
	}else{
		return y;
	}
}

ll dfs(ll depth,int x,int y){
	if(!matrix[x][y])return MAX;
	if(target.first == x && target.second == y)return depth;
	
	ll a,b,c,d;
	a = b = c = d = MAX;
	if(!visited[x+1][y]){
		visited[x+1][y] = true;
		a = dfs(depth+1,x+1,y);
		visited[x+1][y] = false;
	}
	if(!visited[x-1][y]){
		visited[x-1][y] = true;
		b = dfs(depth+1,x-1,y);
		visited[x-1][y] = false;
	}
	if(!visited[x][y+1]){
		visited[x][y+1] = true;
		c = dfs(depth+1,x,y+1);
		visited[x][y+1] = false;
	}
	if(!visited[x][y-1]){
		visited[x][y-1] = true;
		d = dfs(depth+1,x,y-1);
		visited[x][y-1] = false;
	}
	return min(a,min(b,min(c,d)));
}

int main(){
	for(int i=0;i<1001;i++){
		for(int j=0;j<1001;j++){
			matrix[i][j] = visited[i][j] = false;
		}
	}
	
	cin >> h >> w >> n;
	pair<int,int> cheese[10];
	for(int i=1;i<=h;i++){
		for(int j=1;j<=w;j++){
			char input;
			cin >> input;
			switch(input){
				case '.':
					matrix[i][j] = true;
					break;
				case 'X':
					matrix[i][j] = false;
					break;
				case 'S':
					matrix[i][j] = true;
					cheese[0] = make_pair(i,j);
					break;
				default:
					matrix[i][j] = true;
					cheese[input - '0'] = make_pair(i,j);
					break;
			}
		}
	}
	
	ll answer=0;
	for(int i=0;i<n;i++){
		target = cheese[i+1];
		visited[cheese[i].first][cheese[i].second] = true;
		answer += dfs(0,cheese[i].first,cheese[i].second);
		visited[cheese[i].first][cheese[i].second] = false;
	}
	
	cout << answer << endl;
	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", &h, &w, &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;
}

C++: #include<iostream>
#include<vector>
#include<algorithm>
#include<set>
#include<queue>
#include<string>
#include<cstdio>
#include<stack>
#include<cmath>
#include<bitset>
#include<memory>
#include<utility>
#include<map>
using namespace std;
#define FOR(i,m,n) for(i=m;i<n;i++)
#define CLR(a,b) memset(a,b,sizeof(a))
#define ROF(i,m,n) for(i=m;i>=n;i--)
#define BUG cout<<"debug"<<endl;
#define RT return
#define BK break
#define HEAP priority_queue
#define SP " "
#define rd(x) (rand()%(x))
#define lowf(a,b,c) lower_bound(a,b,c)
#define upf(a,b,c) upper_bound(a,b,c)
#define sh(a) cout<<a<<endl
typedef long long LL;
typedef vector<int> VI;
const int INF = 2147483647;
const int NEN = -INF - 1;
const LL LINF = 9223372036854775807;
int W, H, I1, J1,N;char g[1005][1005];
bool vis[1005][1005];
bool can(int x, int y)
{
	return x >= 0 && y >= 0 && x < H&&y < W&&g[x][y]!='X';
}
typedef struct node
{
	int i, j, sum;
	node()
	{
		;
	}
	node(int a, int b, int c)
	{
		i = a; j = b; sum = c;
	}
}node;
queue<node>bfs;
typedef struct pos
{
	int x,y;
}pos;
pos all[10];
int dir[4][2] = { {1,0},{-1,0},{0,1},{0,-1} };
int main()
{
	cin >> H >> W >> N;
	node temp;
	int T,i,j,ans=0;
	FOR(i, 0, H)
	{
		FOR(j, 0, W)
		{
			//cin >> g[i][j];
                  scanf("%c",&g[i][j]);
			if (g[i][j] > '0'&&g[i][j] <='9')
			{
				all[g[i][j] - 48].x = i;
				all[g[i][j] - 48].y = j;
			}
			else if (g[i][j] == 'S')I1 = i, J1 = j;
		}
	}
	FOR(T,0,N)
	{
		CLR(vis, 0);
		while (!bfs.empty())bfs.pop();
		if(T>0)bfs.push(node(all[T].x, all[T].y, 0));
		else bfs.push(node(I1, J1, 0));
		while (!bfs.empty())
		{
			temp = bfs.front();
			bfs.pop();
			if (g[temp.i][temp.j] == T+48+1)
			{
				ans += temp.sum;
				break;
			}
			int k = 4,tx,ty;
			while (k--)
			{
				tx = temp.i + dir[k][0];
				ty = temp.j + dir[k][1];
				if (can(tx, ty) == true&&!vis[tx][ty])
				{
					vis[tx][ty] = 1;
					bfs.push(node(tx, ty, temp.sum + 1));
				}
			}
		}
	}
	cout << ans;
}