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 <algorithm>
# include <vector>
# include <string>
# include <set>
# include <map>
# include <cmath>
# include <iomanip>
# include <functional>
# include <utility>
# include <stack>
# include <queue>
# include <list>
# include <tuple>
# include <unordered_map>
# include <numeric>
# include <complex>
# include <bitset>
# include <random>
# include <chrono>
# include <cstdlib>
# include <tuple>
using namespace std;
using LL = long long;
using ULL = unsigned long long;
constexpr int INF = 2147483647;
constexpr int HINF = INF / 2;
constexpr double DINF = 100000000000000000.0;
constexpr double HDINF = 50000000000000000.0;
constexpr long long LINF = 9223372036854775807;
constexpr long long HLINF = 4500000000000000000;
const double PI = acos(-1);
int dx[4] = { 0,1,0,-1 }, dy[4] = { 1,0,-1,0 };
template <typename T_char>T_char TL(T_char cX) { return tolower(cX); };
template <typename T_char>T_char TU(T_char cX) { return toupper(cX); };
# define ALL(x)      (x).begin(),(x).end()
# define UNIQ(c)     (c).erase(unique(ALL((c))),(c).end())
# define LOWER(s)    transform(ALL((s)),(s).begin(),TL<char>)
# define UPPER(s)    transform(ALL((s)),(s).begin(),TU<char>)
# define FOR(i,a,b)  for(LL i=(a);i<(b);i++)
# define RFOR(i,a,b) for(LL i=(a);i>=(b);i--)
# define REP(i,n)    FOR(i,0,n)
# define INIT        std::ios::sync_with_stdio(false);std::cin.tie(0)

string maze[1001];
int h, w;
int sx, sy, gx, gy;

int d[1001][1001];
int bfs() {
	queue<pair<int, int>> que;
	for (int i = 0; i < h; i++) {
		for (int j = 0; j < w; j++) {
			d[i][j] = HINF;
		}
	}
	que.push(pair<int, int>(sx, sy));
	d[sy][sx] = 0;
	while (que.size()) {
		pair<int, int> p = que.front();
		que.pop();
		for (int i = 0; i < 4; i++) {
			int nx = p.first + dx[i], ny = p.second + dy[i];
			if (0 <= nx&&nx < w && 0 <= ny&&ny < h &&maze[ny][nx] != 'X'&&d[ny][nx] == HINF) {
				que.push(pair<int, int>(nx, ny));
				d[ny][nx] = d[p.second][p.first] + 1;
			}
		}
	}
	return d[gy][gx];
}
int n;

int main() {
	cin >> h >> w >> n;
	REP(i, h)cin >> maze[i];
	LL ans = 0;
	for (int k = 1; k <= n; k++) {
		REP(i, h)REP(j, w) {
			if (k == 1) {
				if (maze[i][j] == 'S') {
					sx = j, sy = i;
				}
				if (maze[i][j] == '1') {
					gx = j, gy = i;
				}
			}
			else {
				if (maze[i][j] == (char)('0' + k - 1)) {
					sx = j, sy = i;
				}
				if (maze[i][j] == (char)('0' + k)) {
					gx = j, gy = i;
				}
			}
		}
		ans += bfs();
	}
	cout << ans << endl;
}

C++: #include <iostream>   
#include <queue>

const int MAX_H = 1000;
const int MAX_W = 1000;
const int a = 100000000;

using namespace std;

typedef pair<int, int> P;


int H = 0, W = 0, N = 0; 
 
int food[11][2];
char cheese[MAX_H][MAX_W] = {0}; 
int r[MAX_H][MAX_W]; 
int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1}; 

int search(int &sx, int &sy, int &ex, int &ey)
{
 
    P p;
    queue<P> que;
    for(int i=0; i<H; i++)
   {
        for(int j=0; j<W; j++)
       {
           r[i][j] = a;

        }
    }
    que.push(P(sx,sy));
    r[sx][sy] = 0;

    while(que.size())
   {  
        p = que.front();
        que.pop();
        if(p.first == ex && p.second == ey)
			break;
	

	    for(int i=0; i<4; i++)
	   {
		    int xn = p.first + dx[i];
		    int yn = p.second + dy[i];


		    if(xn >= 0 && xn < H && yn >= 0 && yn < W && cheese[xn][yn]!='X' && r[xn][yn] == a )
		   {
			    que.push(P(xn,yn));
			    r[xn][yn] = r[p.first][p.second] + 1;
		    }
	    }

	}
	return r[ex][ey];
}

int main()
{
	int dis = 0;
    cin >> H >> W >> N;
    for(int i=0; i<H; i++)
   {
        for(int j=0; j<W; j++)
       {
          cin >> cheese[i][j];
          if(cheese[i][j] == 'S')
         {
             food[0][0] = i;
             food[0][1] = j;
             cheese[i][j] = '.';
          }
          if(cheese[i][j]>48&&cheese[i][j]<58)
         {
             int num = cheese[i][j] - 48;  
             factor[num][0] = i;
             factor[num][1] = j;
          }
       }
    }
   

    for(int i=0; i<N; i++)
   {
       dis += search(food[i][0], food[i][1], food[i+1][0], food[i+1][1]); 
    }
    
	cout << dis << endl;
    return 0;
}

C++: #include <stdio.h>  
#include <string.h>  
#include <queue>  
#define MAX_W 1003 
#define MAX_H 1003
#define MAX_N 9   
using namespace std;  int d[MAX_H][MAX_W];  
char m[MAX_H][MAX_W + 1];  
int w, h, n;  
int gx[MAX_N + 1], gy[MAX_N + 1];  
int dx[] = {0, 0, 1, -1}, dy[] = {1, -1, 0, 0};  
  
int bfs(int sx, int sy, int gx, int gy)  
{   
    queue<int> que;  
    que.push(sx * w + sy);  
    d[sx][sy] = 0;  
          
    while(que.size())  
    {  
        int x = que.front()/w, y = que.front()%w;  
        que.pop();  
        if(x == gx && y == gy)  
            break;  
  
        for(int di = 0; di < 4; ++di){  
            int nx = x + dx[di], ny = y + dy[di];  
            if(nx >= 0 && nx < h && ny >= 0 && ny < w && 'X' != m[nx][ny] && -1 == d[nx][ny]){  
                d[nx][ny] = d[x][y] + 1;  
                que.push(nx * w + ny);  
            }  
        }  
    }  
    return d[gx][gy];  
}  
  
void solve()  
{  
    int ans = 0;  
    for(int i = 0; i < n; i ++)  
        ans += bfs(gx[i], gy[i], gx[i + 1], gy[i + 1]);  
    printf("%d\n", ans);  
}  
  
int main()  
{  
   memset(d, -1, sizeof(d)); 
    scanf("%d%d%d", &h, &w, &n);  
    for(int i = 0; i < h; i ++)  
        scanf("%s", m[i]);  
          
    for(int i = 0; i < h; i ++)  
        for(int j = 0; j < w; j ++){  
            if('1' <= m[i][j] && '9' >= m[i][j])  
                gx[m[i][j] - '0'] = i, gy[m[i][j] - '0'] = j;  
            else if('S' == m[i][j])  
                gx[0] = i, gy[0] = j;  
        }  
  
    if(w || h)  
        solve();  
    return 0;  
}