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 <bits/stdc++.h>
using namespace std;
#define rep(i,n) for(int i=0; i<(n); i++)
#define FOR(i,x,n) for(int i=x; i<(n); i++)
#define ALL(n) begin(n),end(n)
#define MOD (1000000007)
#define INF (1e9)
#define INFL (1e18)

typedef long long ll;
typedef unsigned int ui;
typedef unsigned long long ull;
template<class T>using arr=vector<vector<T>>;
template<class T>void pr(T x){cout << x << endl;}
template<class T>void prvec(vector<T>& a){rep(i, a.size()-1){cout << a[i] << " ";} pr(a[a.size()-1]);}
template<class T>void prarr(arr<T>& a){rep(i, a.size()) if(a[i].empty()) pr(""); else prvec(a[i]);}
template<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; }
template<class T>bool chmin(T &a, const T &b) { if (b<a) { a=b; return 1; } return 0; }
int dx[] = {1, -1, 0, 0};
int dy[] = {0, 0, 1, -1};

using P = pair<int, int>;
void prp(P& p) {cout << p.first << " " << p.second << endl;}
struct root{
    P p;
    int cnt;
};

int H, W, N;
vector<string> field;

P s;

int bfs(P& s,int g){
    queue<root> que;
    arr<bool> seen(H, vector<bool>(W, false));
    seen[s.first][s.second] = true;
    que.push({s, 0});
    bool flag = false;

    while(!que.empty()){
        root rt = que.front(); que.pop();
        P pos = rt.p;
        // prp(pos);
        rep(i, 4){
            int x = pos.first + dx[i];
            int y = pos.second + dy[i];
            if(x < 0 || x >= H || y < 0 || y >= W) continue;
            if(seen[x][y]) continue;
            seen[x][y] = true;

            if(field[x][y]=='X') continue;
            if('1' <= field[x][y] && field[x][y] <= '9'){
                if(field[x][y] - '0' == g){
                    flag = true;
                    s.first = x;
                    s.second = y;
                    return rt.cnt+1;
                }else{
                    que.push({{x, y}, rt.cnt+1});
                }
            }else que.push({{x, y}, rt.cnt+1});
        }
        if(flag) break;
    }
    return -1;
}

int main()
{
    cin >> H >> W >> N;
    rep(i, H) {
        string a; cin >> a;
        field.push_back(a);
        rep(j, W){
            if(a[j] == 'S') s = {i, j};
        }
    }
    int ans = 0;
    rep(i, N){
        ans += bfs(s, i+1);
        // pr(ans);
    }
    
    pr(ans);
    return 0;}

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

typedef struct{
 int x;
 int y;
}P;//表示坐?

char graph[1000][1000];
P aim[10];
P s,g;//s起点，g?点
int N,W,H;
int vis[1000][1000]; //用来存?距?
int dx[]={1,0,-1,0},dy[]={0,1,0,-1};

int bfs(P s,P g);

int main(){
    int i,j,t,step=0;
    cin>>H>>W>>N;

    for(i=0;i<H;i++)
    for(j=0;j<W;j++){
        cin>>graph[i][j];
      if(graph[i][j]<='9'&&graph[i][j]>='1'){
         t=graph[i][j]-'0';
         aim[t].x=i;
         aim[t].y=j;
      } //把1-N的坐?保存在 aim数?中
      else if(graph[i][j]=='S'){
          s.x=i;
          s.y=j;
          graph[i][j]='.';
      }//得到最初的起点
    }

    for(i=1;i<=N;i++){
       g.x=aim[i].x;
       g.y=aim[i].y;//1-N ，从小到大，?次把一个 作??点
       step+=bfs(s,g);
       s.x=g.x;
       s.y=g.y;//到??个?点后??点?起点
       graph[g.x][g.y]='.';
    }

    cout<<step<<endl;
     /*for(int i=0;i<H;i++)
        {
            for(int j=0;j<W;j++)
            {
                printf("%c",graph[i][j]);
            }
            printf("\n");
        }
        */
}

int bfs(P s,P g){
    queue<P> que;
      P n;

    for(int i=0;i<H;i++)
    for(int j=0;j<W;j++)
     vis[i][j]=-1;

     que.push(s);
     vis[s.x][s.y]=0;

     while(que.size()){

       P p=que.front();
         que.pop();
       if(p.x==g.x&&p.y==g.y)
       break;

       for(int i=0;i<4;i++){
           n.x=p.x+dx[i];
           n.y=p.y+dy[i];//向四方漫射
        if(0<=n.x&&n.x<H&&0<=n.y&&n.y<W&&graph[n.x][n.y]!='X'&&vis[n.x][n.y]==-1){
               que.push(n);
               //graph[n.x][n.y]='#';
               vis[n.x][n.y]=vis[p.x][p.y]+1;
           }
       }
   }
     return vis[g.x][g.y];
}