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 <ctype.h>
#include <queue>
#define INF 1000000
using namespace std;
 
int dx[4] = { 1, 0, -1, 0 }; //
int dy[4] = { 0, 1, 0, -1 };
int H, W, N, res;
int d[1000][1000];
char HW[1000][1000];
 
int bfs(int sH, int sW, int gH, int gW) {
    typedef pair <int, int> P;
    queue <P> Q;
    for (int i = 0; i < H; i++) {
        for (int j = 0; j < W; j++) d[i][j] = INF;
    }
    Q.push(P(sH, sW));
    d[sH][sW] = 0;
 
    while (Q.size()) {
        P p = Q.front(); Q.pop();
        if (p.first == gH && p.second == gW) break;
        for (int i = 0; i < 4; i++) {
            int nH = p.first + dy[i], nW = p.second + dx[i];
            if (0 <= nW && nW <= W - 1 && 0 <= nH && nH <= H - 1 && HW[nH][nW] != 'X' && d[nH][nW] == INF) {
                Q.push(P(nH, nW));
                d[nH][nW] = d[p.first][p.second] + 1;
            }
        }
    }
    return d[gH][gW];
}
 
int main() {
    typedef pair <int, int> P;
    P num[10]; //
    cin >> H >> W >> N;
    for (int i = 0; i < H; i++) {
        for (int j = 0; j < W; j++) {
            cin >> HW[i][j];
            if (HW[i][j] == 'S') {
                num[0].first = i;
                num[0].second = j;
            }
            if (isdigit(HW[i][j])) {
                num[HW[i][j] - '0'].first = i;
                num[HW[i][j] - '0'].second = j;
            }
        }
    }
    for (int i = 0; i < N; i++) {
        res += bfs(num[i].first, num[i].second, num[i + 1].first, num[i + 1].second);
    }
    cout << res << "\n";
    // for (int i = 0; i < N + 1; i++) cout << num[i].first << " " << num[i].second << "  ";
    
    // getchar(); getchar();
    return 0;
}

C++: #include <bits/stdc++.h>
using namespace std;

int h, w, n;
char m[1010][1010];
int d[1010][1010];
int dx[] = {0, 0, 1, -1}, dy[] = {1, -1, 0, 0};

void init()
{
  for (int i = 0; i < h; i++){
    for (int j = 0; j < w; j++){
      d[i][j] = 1e9 + 9;
    }
  }
}

int main()
{
  int sx, sy;

  cin >> h >> w >> n;
  for (int i = 0; i < h; i++){
    for (int j = 0; j < w; j++){
      cin >> m[i][j];
      if (m[i][j] == 'S') sx = j, sy = i;
    }
  }

  int ans = 0;
  for (int i = 1; i <= n; i++){
    queue<pair<int, int> > q;
    q.push(make_pair(sy, sx));

    init();
    d[sy][sx] = 0;
    while (!q.empty()){
      pair<int, int> nv = q.front();
      q.pop();

      if (m[nv.first][nv.second] == '0' + i){
        sy = nv.first;
        sx = nv.second;
        ans += d[sy][sx];
        while (!q.empty()) q.pop();
        break;
      }

      for (int j = 0; j < 4; j++){
        int ny = nv.first + dy[j];
        int nx = nv.second + dx[j];
        if (ny < 0 || h <= ny || nx < 0 || w <= nx) continue;
        if (d[ny][nx] < d[nv.first][nv.second]) continue;
        if (m[ny][nx] == 'X') continue;
        d[ny][nx] = d[nv.first][nv.second] + 1;
        q.push(make_pair(ny, nx));
      }
    }
  }

  cout << ans << endl;
}

C++: #include <iostream>
#include <stdio.h>
#include <cstring>
#include <queue>
using namespace std;

char ma[1005][1005];int vis[1005][1005];
int w,h,n;

int dx[]={1,0,-1,0};
int dy[]={0,1,0,-1};

struct node
{
    int x,y,time;
};
node start;

void bfs(char ed)
{
    queue<node> que;
    que.push(start);
    vis[start.x][start.y]=1;
    while(!que.empty())
    {
        node no=que.front();
        que.pop();
        for(int i=0;i<4;i++)
        {
            int x=no.x+dx[i];
            int y=no.y+dy[i];
            if(vis[x][y]||x>=h||x<0||y>=w||y<0||ma[x][y]=='X')
                continue;
            if(ma[x][y]==ed)
            {
                start.x=x;
                start.y=y;
                start.time=no.time+1;
                return ;
            }
            vis[x][y]=1;
            node no1;
            no1.x=x;no1.y=y;no1.time=no.time+1;
            que.push(no1);
        }
    }
}

int main()
{
    while(~scanf("%d %d %d\n", & h, & w, & n))
    {
        for(int i=0;i<h;i++)
        {
            //scanf("%s",&ma[i]);
            gets(ma[i]);
for(int j=0;j<w;j++)
                if(ma[i][j]=='S')
                {
                    start.x=i;
                    start.y=j;
                    start.time=0;
                }

        }
            for(int i=0;i<n;i++)
            {
                memset(vis,0,sizeof(vis));
                bfs(i+'1');
            }

            printf("%d\n",start.time);
    }
    return 0; 
}

C++: #include<iostream>
#include<utility>
#include<vector>

using namespace std;

int H, W, N;
char mapT[1000][1000];
char temp_map[1000][1000];

int temp_x = 0, temp_y;
char temp;
int min_rou = 0;
int min_route = 500000;
int final_min_route = 0;
vector<pair<int, int> > dir;

void findSmallRoute(int x, int y, char &factory) {
	if (mapT[x][y] == factory) {
		++min_rou;
		if (min_route > (min_rou-1)) {
			min_route = min_rou - 1;
			temp_x = x;
			temp_y = y;
		}
		--min_rou;
		return;
	}
	if (x < 0 || y >= W || x >= H || y < 0 || mapT[x][y] == 'X') {
		return;
	}
	++min_rou;
	mapT[x][y] = 'X';
	for (vector<pair<int, int> >::iterator it = dir.begin(); it != dir.end(); ++it) {
		findSmallRoute(x + it->first, y + it->second, factory);
		
	}
	mapT[x][y] = temp_map[x][y];
	--min_rou;
	return;
}

int main() {
	dir.push_back({ -1,0 });
	dir.push_back({ 0,1 });
	dir.push_back({ 1,0 });
	dir.push_back({ 0,-1 });
	int start_X = 0, start_Y = 0;
	cin >> H >> W >> N;
	for (int i = 0; i < H; i++) {
		for (int j = 0; j < W; ++j) {
			cin >> temp;
			mapT[i][j] = temp;
			if (temp == 'S') {
				start_X = i;
				start_Y = j;
			}
		}
	}

	for (int i = 0; i < H; ++i) {
		for (int j = 0; j < W; ++j) {
			temp_map[i][j] = mapT[i][j];
		}
	}

	for (int factory = 1; factory != N + 1; ++factory) {
		
		char n = factory + '0';
		findSmallRoute(start_X, start_Y, n);
		for (int i = 0; i < H; ++i) {
			for (int j = 0; j < W; ++j) {
				mapT[i][j] = temp_map[i][j];
			}
		}
		final_min_route += min_route;
		min_rou = 0;
		min_route = 500000;
		
		start_X = temp_x;
		start_Y = temp_y;
	}

	cout << final_min_route << endl;
	//system("pause");
	return 0;
}