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>

#define rep(i,a,b) for(int i=(a);i<(b);i++)
#define pb push_back
#define mp(a,b) make_pair(a,b)
#define all(a) a.begin(),a.end()
#define pii pair<int, int>
#define ll long long
using namespace std; 

#define MAX 10
#define SIZE 1000
#define INF 1<<30

int H, W, N;
char sec[SIZE][SIZE+1];
int move_cnt = INF;
int all_move_cnt = 0;
int dy[4] = {-1, 0, 1, 0};
int dx[4] = {0, 1, 0, -1};
int facy[10] = {};
int facx[10] = {};

struct state {
	int sy, sx, gy, gx, cnt;
	state() {}
	state(int _sy, int _sx, int _gy, int _gx, int _cnt) :
		sy(_sy), sx(_sx), gy(_gy), gx(_gx), cnt(_cnt) {}
};
queue<state> que;

void bfs()
{
	int **tsec = new int*[SIZE];
	rep(i,0,SIZE) tsec[i] = new int[SIZE+1];
	rep(i,0,SIZE) rep(j,0,SIZE+1) tsec[i][j] = INF;

	while (!que.empty()) {
		state ts = que.front(); que.pop();
		// printf("sy=%d sx=%d gy=%d gx=%d cnt=%d\n",ts.sy,ts.sx,ts.gy,ts.gx,ts.cnt);
		if (ts.cnt > move_cnt) return;
		if (ts.sy == ts.gy && ts.sx == ts.gx) {
			move_cnt = min(move_cnt, ts.cnt);
			return;
		}
		tsec[ts.sy][ts.sx] = ts.cnt;

		rep(i, 0, 4) {
			int ny = ts.sy + dy[i];
			int nx = ts.sx + dx[i];
			if (ny < 0 || ny >= H) continue;
			if (nx < 0 || nx >= W) continue;
			if (sec[ny][nx] == 'X') continue;
			if (tsec[ny][nx] < ts.cnt) continue; 
			state ns(ny, nx, ts.gy, ts.gx, ts.cnt + 1);
			que.push(ns);
		}
	// rep(i,0,H) { rep(j,0,W) tsec[i][j]>99? printf("99"):printf("%2d",tsec[i][j]); cout << endl;}
	}

	rep(i,0,SIZE) delete[] tsec[i];
	delete[] tsec;
}

void solve()
{
	// rep(i,0,N+1) printf("%d y=%d x=%d\n",i,facy[i],facx[i]);

	rep(i,0,N) {
		move_cnt = INF;
		while(!que.empty()) que.pop();
		state s(facy[i], facx[i], facy[i+1], facx[i+1], 0);
		que.push(s);
		// printf("\n bfs start !! \n");
		bfs();
		all_move_cnt += move_cnt;
	}

	cout << all_move_cnt << endl;
}

void input()
{
	cin >> H >> W >> N;
	rep(i,0,H) { 
		rep(j,0,W) {
			cin >> sec[i][j];
			if (sec[i][j] == 'S') { facy[0] = i; facx[0] = j; }
			if (sec[i][j] >= 49 && 57 >= sec[i][j]) {
				facy[sec[i][j]-48] = i;
				facx[sec[i][j]-48] = j;
			}
		}
	}
	solve();
}

int main(void)
{
	input();
	
	return 0;
}

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

const int MAX=1010;
char map[MAX][MAX];
int vis[MAX][MAX];
int  h,w,n;
int sx,sy;
int e[MAX][3];
int fx[]={1,-1,0,0};
int fy[]={0,0,1,-1};
struct node
{
    int x,y,step;
};
int bfs(int x,int y,int ex,int ey)
{
    memset(vis,0,sizeof(vis));
    vis[x][y]=1;
    node a;
    a.x=x,a.y=y,a.step=0;
    queue<node>Q;
    Q.push(a);
    while(!Q.empty())
    {
        node p=Q.front();
        Q.pop();
        if(p.x==ex&&p.y==ey)
        {
            sx=p.x,sy=p.y;
            return p.step;
        }
        for(int i=0;i<4;++i )
        {
            int tx=p.x+fx[i];
            int ty=p.y+fy[i];
            if(tx<1||tx>h||ty<1||ty>w||vis[tx][ty]||map[tx][ty]=='X')
                continue;
            vis[tx][ty]=1;
            node s;
            s.x=tx,s.y=ty,s.step=p.step+1;
            Q.push(s);
        }
    }

}
int main()
{
    while(scanf("%d%d%d",&h,&w,&n)!=EOF)
    {
        if(n==0&&w==0)
            break;
        for(int i=1;i<=h;++i)
        {
            scanf("%s",map[i]+1);
            for(int j=1;j<=w;++j)
            {
                if(map[i][j]=='S')
                {
                    sx=i,sy=j;
                }
                else if(map[i][j]!='X'&&map[i][j]!='.')
                {
                    e[map[i][j]-'0'][0]=i;
                    e[map[i][j]-'0'][1]=j;
                }
            }
        }
        int ans=0;
        for(int i=1;i<=n;++i)
        {
            ans+=bfs(sx,sy,e[i][0],e[i][1]);
        }
        printf("%d\n",ans);
    }
    return 0;
}