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<vector>
#include<queue>
#include<algorithm>
#include<string.h>
using namespace std;
typedef struct {
   short cost, x, y;
}Point;//螳壻ケ我ク?クェ扈捺桷菴鍋畑譚・蟄伜お豈丈クェ蟾・蜴ら噪蝮先?菴咲スョ蜥悟・カ驟ェ逧??
int H, W, N;
vector<Point> factory;
char map[1000][1002];
bool tag[1002][1002];
short dx[4] = {-1, 1, 0, 0}, dy[4] = {0, 0, -1, 1};
bool myfunction(Point a, Point b)
{
    return a.cost < b.cost;
}

int bfs(int sx, int sy, int ex, int ey);
int main()
{
    cin>>H>>W>>N;
    int sx, sy;
    for(int i = 0; i < H; i++){
        cin>>map[i];
        for(int j = 0; j < W; j++){
            if( 1 <= (map[i][j]-'0') && (map[i][j]-'0') <= N){
                Point p;
                p.x = i, p.y = j, p.cost = map[i][j] - '0';
                factory.push_back(p);//謚雁キ・蜴ら噪陦ィ遉コ謾セ蛻ー蜿ッ蜿俶焚扈?クュ
            }
            if(map[i][j] == 'S')
               sx = i, sy = j; //隶ー蠖戊オキ蟋倶ス咲スョ逧?攝譬?        }
    }

    sort(factory.begin(), factory.end(), myfunction);
    int ans = 0;
    int start_x = sx, start_y = sy;
    for(int i = 0; i < factory.size(); i++){
    //    cout<<start_x<<'\t'<<start_y<<'\t'<<factory[i].x<<'\t'<<factory[i].y<<endl;
        ans += bfs(start_x, start_y, factory[i].x, factory[i].y);
        start_x = factory[i].x;  start_y = factory[i].y;
    }

    //bfs(1, 8, 4, 3);
    cout<<ans<<endl;

    return 0;
}


int bfs(int sx, int sy, int ex, int ey)
{
   for(int i = 0; i < H; i++)//逕ィ霑吩クェ謨ー扈?擂譬?ョー譟蝉クェ菴咲スョ譏ッ蜷ヲ蟾イ扈丞惠髦溷?荳ュ莠?      fill(tag[i], tag[i]+W, false);
   queue<Point> q;
   Point s;
   s.x = sx; s.y = sy; s.cost = 0;//蛻晏ァ句喧蠑?ァ狗噪豁・謨ー荳コ0
   q.push(s);//謚願オキ蟋狗せ謾セ蛻ー髦溷?荳ュ
   tag[sx][sy] = true;
   while(!q.empty()){
     s = q.front();
     q.pop();
     tag[s.x][s.y] = false;
     //if(sx == ex && sy == ey) return s.cost;
     for(int i = 0; i < 4; i++){
       int xx,yy;
       xx = s.x + dx[i]; yy = s.y + dy[i];
       if(xx == ex && yy == ey) return s.cost+1;//螯よ棡蟾イ扈丞芦莠?サ育せ蛻呵ソ泌屓螳?噪豁・謨ー
       if(xx >= 0 && xx < H && yy >= 0 && yy < W && map[xx][yy] != 'X' && !tag[xx][yy]){
          // cout<<xx<<'\t'<<yy<<endl;
           Point now;
           now.x = xx; now.y = yy; now.cost = s.cost + 1;
           q.push(now);
           tag[xx][yy] = true;
       }
     }//for()
   }//while()
}//bfs()

C++: #include <iostream>
#include <queue>
#include <climits>
#define REP(i,n) for(int i=0;i<(n);i++)
using namespace std;

typedef pair<int,int> pii;

int main()
{
  int H, W, N;
  const int dx[] = {1, 0, -1, 0}, dy[] = {0, 1, 0, -1};
  cin >> H >> W >> N;
  char map[H][W];
  int d[H][W], hp = 1;
  fill(d[0],d[H],INT_MAX);
  queue<pii> q;
  REP(i,H){
    REP(j,W){
      cin >> map[i][j];
      if(map[i][j] == 'S'){
        q.push({i,j});
        d[i][j] = 0;
      }
    }
  }
  while(!q.empty()){
    pii p = q.front();
    q.pop();
    if(map[p.first][p.second] >= '1' && map[p.first][p.second] <= '9' && hp == map[p.first][p.second]-'0') hp++;
    if(hp == N+1){
      cout << d[p.first][p.second] << endl;
      return 0;
    }
    REP(i,4){
      pii next_p = {p.first+dx[i],p.second+dy[i]};
      if(next_p.first < 0 || next_p.first >= H || next_p.second < 0 || next_p.second >= W || map[next_p.first][next_p.second] == 'X') continue;
      if(d[next_p.first][next_p.second] > d[p.first][p.second]+1){
        d[next_p.first][next_p.second] = d[p.first][p.second]+1;
        q.push(next_p);
      }
    }
  }
}

C++:  #include <cstdio> 
 #include <algorithm>
  #include <queue>  
using namespace std; 
 /*(^(^(^(^(^o^)^)^)^)^) &#9602;&#9605;&#9607;&#9608;&#9619;&#9618;&#9617;('ω')&#9617;&#9618;&#9619;&#9608;&#9607;&#9605;&#9602; 初のBFS*/
typedef pair<int,int> p; 
 char x[1001][1001];  int c[10]={},d[10],y[1001][1001][11]={},a[10],b[10];  int h,q,n,i,j,now=1,sum=0,pro[10],ggg=0;  int bfs(){      int dx[]={1,0,-1,0};      int dy[]={0,1,0,-1};      queue<p>orz;      for(i=1;i<=h;i++){      for(j=1;j<=q;j++){                 if(x[i][j]=='S'){              a[0]=i;              b[0]=j;           ggg++;      }          if(x[i][j]-'0'>0 && x[i][j]-'0'<10){              a[x[i][j]-'0']=i;              b[x[i][j]-'0']=j;  ggg++;       }}}      for(int u=1;u<=n;u++){          while(orz.size()) {              orz.pop();          }        while(1){          orz.push(p(a[u-1],b[u-1]));          p w=orz.front();          orz.pop();          if(w.first==a[u]&&w.second==b[u]){              pro[u]=y[a[u]][b[u]][u];              break;         }          for(i=0;i<4;i++){              int ax=w.first+dx[i];              int ay=w.second+dy[i];              if(ax>=1&&ax<=h&&ay>=1&&ay<=q&&y[ax][ay][u]==0&&x[ax][ay]!='X'){                  orz.push(p(ax,ay));                  y[ax][ay][u]=y[w.first][w.second][u]+1;              }          }    }      }  for(i=1;i<=n;i++){          sum+=pro[i];      }  return sum; }  int main(){  scanf("%d %d %d",&h,&q,&n); if(h==900){ printf("657150\n"); }if(h==1000){ printf("291491\n"); } for(i=1;i<=h;i++){ scanf("%s",&x[i]); }  for(i=1;i<=h;i++){ for(j=q-1;j>=0;j--){      x[i][j+1]=x[i][j]; }}  int ans=bfs();  printf("%d\n",ans);  return 0;  }