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<iomanip>
#include<map>
#include<set>
#include<string>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<stack>
 
using namespace std;
 
#define P(p) cout<<(p)<<endl
#define rep(i,m,n) for(int i = (m); i < (int)(n); i++)
#define rrep(i,m,n) for(int i=(int)(m); i>=(int)(n); i--)
#define vsort(v) sort(v.begin(), v.end());
#define rvsort(v) sort(v.begin(), v.end(),greater<int>());
#define YES cout<<"YES"<< endl
#define NO cout<<"NO"<<endl
#define Yes cout<<"Yes"<<endl
#define No cout<<"No"<<endl  
#define yes cout<<"yes"<<endl
#define no cout<<"no"<<endl
#define ret return
#define C(i) cin>>i
#define C2(i,j) cin>>i>>j
#define C3(i,j,k) cin>>i>>j>>k
#define C4(i,j,k,m) cin>>i>>j>>k>>m
////////////////////////////////////////////////////////////

struct S{
  int num;
  int x;
  int y;
};

int main(){
  int h,w,n;
  C3(h,w,n);
  
  int f[h][w] = {};
  pair<int,int> g[n+1];
  pair<int,int> s[n+1];
  rep(i,0,h){
    rep(j,0,w){
      char c;
      cin >> c;
      if(c == 'X'){
        f[i][j] = -1;
      }
      else if(c == '.'){
        f[i][j] = 0;
      }
      else if(c == 'S'){
        pair<int,int> tt = {j,i};
        s[1] = tt;
      }
      else{
        int t = c - '0';
        f[i][j] = t;
        pair<int,int> tt = {j,i};
        g[t] = tt;
        
        if(t < n){
          s[t+1] = tt;
        }

      }
    }
  }

  int ans = 0;
  rep(i,1,n+1){
    int sx = s[i].first;
    int sy = s[i].second;
    int gx = g[i].first;
    int gy = g[i].second;
    //printf("sx:%d sy:%d gx:%d gy:%d\n",sx,sy,gx,gy);
    queue<struct S> q;
    struct S tmp = {0,sx,sy};
    q.push(tmp);
    
    int fNum[h][w];
    rep(i,0,h)
      rep(j,0,w)
      fNum[i][j] = 0xFFFF;
    

    while(!q.empty()){
      struct S s = q.front();
      //printf("i:%d n:%d x:%d y:%d\n",i,s.num,s.x,s.y);
      q.pop();
      if(f[s.y][s.x] == -1){
        continue;
      }
      if(s.num >= fNum[s.y][s.x] && s.num != 0)
        continue;

      fNum[s.y][s.x] = s.num;
      if(s.y == gy && s.x == gx)
        continue;

      else{
        if(s.y > 0){
          if(f[s.y-1][s.x] != -1&& fNum[s.y-1][s.x] > s.num+1){
            struct S t = {s.num+1,s.x,s.y-1};
            q.push(t);
          }
        }
        if(s.x + 1 <= w - 1 ){
          if(f[s.y][s.x+1] != -1 && fNum[s.y][s.x+1] > s.num+1){
            struct S r = {s.num+1,s.x+1,s.y};
            q.push(r);
          }
        }
        if(s.x > 0){
          if(f[s.y][s.x-1] != -1 && fNum[s.y][s.x-1] > s.num+1){
            struct S l = {s.num+1,s.x-1,s.y};
            q.push(l);
          }
        }
        if(s.y + 1 <= h -1 ){
          if(f[s.y+1][s.x] != -1 && fNum[s.y+1][s.x] > s.num+1){
            struct S b = {s.num+1,s.x,s.y+1};     
            q.push(b);
          }
        }
      }
    }

    ans += fNum[gy][gx];
  }

  P(ans);

  ret 0;
}

C++: #include<iostream>
using namespace std;
const int MAXN=1000+5;
int H,W,n,totime;
char maze[MAXN][MAXN],d[MAXN][MAXN];
int fx[9+2],fy[9+2],sx,sy;
int dx[4]={1,0,-1,0};
int dy[4]={0,1,0,-1};
void input(){
	cin>>H>>W>>n;
	for(int i=0;i<H;i++){
		for(int j=0;j<W;j++){
			cin>>maze[i][j];
			if('0'<=maze[i][j] && maze[i][j]<='9'){
				fx[maze[i][j]-'0']=i;
				fy[maze[i][j]-'0']=j;
			}
			if(maze[i][j]=='S'){
				sx=i;
				sy=j;
			}
		}
	}
}
void bfs(){
	for(int i=1;i<=n;i++){
		int qx[260565],qy[260565];
		int front=0,rear=0;
		for(int a=0;a<H;a++)
			for(int b=0;b<W;b++)
				d[a][b]='#';
		d[sx][sy]='0';
		qx[rear]=sx;
		qy[rear]=sy;
		rear++;
		while(front<rear){
			int x=qx[front],y=qy[front];
			front++;
			if(x==fx[i] && y==fy[i]){
				sx=fx[i];
				sy=fy[i];
				break;
			}
			for(int j=0;j<4;j++){
				int tx=x+dx[j],ty=y+dy[j];
				if(tx>=0 && tx<H && ty>=0 && ty<W &&
				maze[tx][ty]!='X' && d[tx][ty]=='#'){
					qx[rear]=tx;
					qy[rear]=ty;
					rear++;
					d[tx][ty]=d[x][y]+1;
				}
			}
		}
		totime+=d[fx[i]][fy[i]]-'0';
	}
}
void output(){
	cout<<totime<<endl;
}
void solve(){
	input();
	bfs();
	output();
}
int main(){
	solve();
	return 0;
}

C++: #include<bits/stdc++.h>
using namespace std;
const int dx[]={1,0,-1,0};
const int dy[]={0,1,0,-1};
const int MAXN=1000+20;
int dp[MAXN][MAXN];
int maze[MAXN][MAXN];
int h,w,n,sx[10],sy[10],temp;
void input(){
	memset(maze,-1,sizeof(maze));
	cin>>h>>w>>n;
	cin.get();
	for(int i=1;i<=h;++i){
		for(int j=1;j<=w;++j){
			char x;
			x=cin.get();
			if(x=='.') maze[i][j]=0;
			if(x=='X') maze[i][j]=-1;
			if(x>='0' && x<='9'){
				maze[i][j]=x-'0';
				sx[x-'0']=i;
				sy[x-'0']=j;
			}
			if(x=='S'){
				maze[i][j]=0;
				sx[0]=i;
				sy[0]=j;
			}
		}
		cin.get();
	}
//	for(int i=0;i<10;++i) cout<<sx[i]<<' '<<sy[i]<<endl;
/*	for(int i=1;i<=h;++i){
		for(int j=1;j<=w;++j){
			cout<<setw(4)<<maze[i][j];
		}
		cout<<endl;
	}*/
}
void bfs(int xx,int yy,int nn){
	queue <int> tx;
	queue <int> ty;
	tx.push(xx);
	ty.push(yy);
	while(tx.size() && ty.size()){
		int qx=tx.front(),qy=ty.front();
		tx.pop();
		ty.pop();
		for(int i=0;i<4;++i){
			int x=qx+dx[i],y=qy+dy[i];
			if(maze[x][y]==-1 || dp[x][y]>=0) continue;
			tx.push(x);
			ty.push(y);
			dp[x][y]=dp[qx][qy]+1;
			if(x==sx[nn] && y==sy[nn]){
				temp=dp[qx][qy];
//				cout<<temp<<endl;
				break;
			}
//			cout<<x<<' '<<y<<' '<<dp[x][y]<<endl;
		}
	}
//	cout<<endl;
}
void solve(){
	for(int i=0;i<n;++i){
//		cout<<temp<<endl;
		memset(dp,-1,sizeof(dp));
//		cout<<sx[i+1]<<' '<<sy[i+1]<<endl;
		dp[sx[i]][sy[i]]=temp;
		bfs(sx[i],sy[i],i+1);
	}
	cout<<dp[sx[n]][sy[n]]+n-1<<endl;
}
int main(){
	input();
	solve();
	return 0;
}