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 <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <queue>

using namespace std;
typedef pair<int, int> pii;

#define S 'S'
#define X 'X'

#define W_MAX 1000

char map[W_MAX][W_MAX];
bool visited[W_MAX][W_MAX];

int main(){
  int H, W, N;
  cin >> H >> W >> N;

  pii pos; //rat position

  for(int i=0; i<H; i++){
    getchar();
    for(int j=0; j<W; j++){
      scanf("%c", &map[i][j]);
      if(map[i][j]==S){
	pos = make_pair(i,j);
      }
    }
  }

  int dx[] = {0, -1, 0 ,1}; int dy[] = {-1, 0, 1, 0};
  int ans=0;
  int next = 1; //next target num

  while(next <= N){
    for(int i=0; i<H; i++)
      for(int j=0; j<W; j++)
	visited[i][j]=false;

    queue<pair<pii, int> > q; //<pos, depth>
    q.push(make_pair(pos, 0));

    while(true){
      pair<pii, int> p = q.front(); q.pop();
      bool found = false;
      visited[p.first.first][p.first.second] = true;
      for(int i=0; i<4; i++){
	int nx = p.first.first + dx[i], ny=p.first.second + dy[i];
	if(nx>=0 && nx<H && ny>=0 && ny<W && visited[nx][ny]==false){
	  visited[nx][ny]= true;
	  if(map[nx][ny] == '0' + next){
	    found = true;
	    pos = make_pair(nx, ny);
	    break;
	  } else if(map[nx][ny]!=X){
	    q.push(make_pair(make_pair(nx, ny), p.second+1));
	  }
	}
      }
      if(found){
	ans += p.second+1;
	next++;
	break;
      }
    }
    while(!q.empty()) q.pop();
  }

  cout << ans << endl;

}

C++: #include <iostream>
#include <queue>
using namespace std;
int w, h, n;
char map[1024][1024];
// 各点到当前工厂的距&#31163;
int d[1024][1024];
const int direction[4][2] = {
    { -1, 0 },
    { 1, 0 },
    { 0, -1 },
    { 0, 1 },
};
 
int factory[16][2];
typedef pair<int, int> P;
 
 
 
//************************************
// Method:    bfs
// FullName:  bfs
// Access:    public 
// Returns:   int
// Qualifier:
// Parameter: const int & sx 起点x
// Parameter: const int & sy 起点y
// Parameter: const int & gx &#32456;点x
// Parameter: const int & gy &#32456;点y
//************************************
int bfs(const int sx, const int sy, const int&gx, const int gy)
{
    //memset(d, -1, sizeof(d));
    for (int i = 0; i < h; ++i)
    {
        for (int j = 0; j < w; ++j)
        {
            d[j][i] = -1;
        }
    }
    queue<P> que;
    que.push(P(sx, sy));
    d[sx][sy] = 0;
    while (que.size())
    {
        const P p = que.front(); que.pop();
        // 如果是&#32456;点就&#32467;束
        if (p.first == gx && p.second == gy)
        {
            break;
        }
 
        // 四方向漫游
        for (int i = 0; i < 4; ++i)
        {
            int nx = p.first + direction[i][0];
            int ny = p.second + direction[i][1];
            // 是否可以移&#21160;，并且&#35813;点没有&#35775;&#38382;&#36807;
            if (0 <= nx && nx < w && 0 <= ny && ny < h && map[nx][ny] != 'X' && d[nx][ny] == -1)
            {
                que.push(P(nx, ny));
                d[nx][ny] = d[p.first][p.second] + 1;
            }
        }
    }
 
    return d[gx][gy];
}
 
///////////////////////////SubMain//////////////////////////////////
int main(int argc, char *argv[])
{
 
    cin >> h >> w >> n;
    for (int i = 0; i < h; ++i)
    {
        for (int j = 0; j < w; ++j)
        {
            cin >> map[j][i];
        }
    }
 
    for (int i = 0; i < h; ++i)
    {
        for (int j = 0; j < w; ++j)
        {
            if (map[j][i] == 'S')
            {
                factory[0][0] = j;
                factory[0][1] = i;
                map[j][i] = '.';
            }
            else if (isdigit(map[j][i]))
            {
                int index = map[j][i] - '0';
                factory[index][0] = j;
                factory[index][1] = i;
            }
        }
    }
 
    int step = 0;
    for (int i = 0; i < n; ++i)
    {
        // 按&#39034;序吃遍中&#21326;
        step += bfs(factory[i][0], factory[i][1], factory[i + 1][0], factory[i + 1][1]);
    }
     
    cout << step << endl;
 
    return 0;
}

C++: #include<iostream>
#include<cstring>
#include<queue>
using namespace std ;
struct ST
{
	int x ;
	int y ;
	int cnt = 0 ;
} ;
bool came[ 1000 ][ 1000 ] = {{ 0 }} ;
char str[ 1000 ] ;
int main()
{
	ST m ,s ;
	queue< ST > que ;
	int n ;
	int w ,h ;
	int kyori = 0 ;
	int min = 1000 ;
	int map[ 1000 ][ 1000 ] = {{ 0 }} ;
	int mx[ 4 ] = { 0 ,0 ,1 ,-1 } ;
	int my[ 4 ] = { 1 ,-1 ,0 ,0 } ;
	cin >> h >> w >> n ;
	int cheesuu = n ;
	int cheese ;
	int fx ,fy ;
	for( int i = 0 ; i < h ; i++ )
	{
		cin >> str ;
		for( int j = 0 ; j < w ; j++ )
		{
			if( str[ j ] == 'X' )
				map[ i ][ j ] = -1 ;
			else if( str[ j ] == 'S' )
			{
				m.x = j ;
				m.y = i ;
			}
			else if( str[ j ] != '.' )
			{
				map[ i ][ j ] = str[ j ] - 48 ;
			}
		}
	}
	que.push( m ) ;
	while( n > 0 )
	{
		n-- ;
		cheese = cheesuu - n ;
		while( !que.empty() )
		{
			m = que.front() ;
			que.pop() ;
			came[ m.y ][ m.x ] = 1 ;
			if( map[ m.y ][ m.x ] == cheese )
			{
				fx = m.x ;
				fy = m.y ;
				min = min > m.cnt ? m.cnt : min ;
			}
			for( int i = 0 ; i < 4 ; i++ )
			{
				if( m.x + mx[ i ] > -1 && m.x + mx[ i ] < w && m.y +  my[ i ] > -1 && m.y + my[ i ] < h )
				{
					s = m ;
					s.x += mx[ i ] ;
					s.y += my[ i ] ;
					s.cnt++ ;
					if( map[ s.y ][ s.x ] != -1 && came[ s.y ][ s.x ] == 0 )
					{
						que.push( s ) ;
					}
				}
			}
		}
		memset( came ,0 ,sizeof( came ) ) ;
		kyori += min ;
		min = 1000 ;
		m.x = fx ;
		m.y = fy ;
		m.cnt = 0 ;
		que.push( m ) ;
	}
	cout << kyori << endl ;
	return 0 ;
}