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<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;
}

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

int h,w,n;
int inf = 0x3f3f3f3f;
char s[1005][1005];
// int vis[1005][1005];
int d[1005][1005];
int dx[] = {-1,0,1,0};
int dy[] = {0,-1,0,1};
struct node{
    int x,y,st;
    node(int q,int qq){
        x = q;
        y = qq;
        st = 0;
    }
};
queue <node> q;

void bfs(int sx,int sy,int ex,int ey){
    while(!q.empty()){
        node no = q.front();
        if(no.x == ex && no.y == ey){
            break;
        }
        // vis[no.x][no.y] = 1;
        q.pop();
        for(int i=0;i<4;i++){
            int xx = no.x + dx[i];
            int yy = no.y + dy[i];
            if(xx>=0 && xx<h && yy>=0 && yy<w){
                if(d[xx][yy]==inf && s[xx][yy]!='X'){
                    d[xx][yy] = d[no.x][no.y] + 1;
                    q.push(node (xx,yy));
                }
            }
        }
    }
}

int ss[10];
int ee[10];

void dea(){
    for(int i=0;i<1005;i++){
        for(int j=0;j<1005;j++){
            d[i][j] = inf;
        }
    }
    // memset(vis,0,sizeof(vis));
    while(!q.empty()){
        q.pop();
    }
}
int main(){
    while(~scanf("%d%d%d",&h,&w,&n)){
        memset(ss,0,sizeof(ss));
        memset(ee,0,sizeof(ee));
        for(int i=0;i<h;i++){
            scanf("%s",&s[i]);
            for(int j=0;j<w;j++){
                if(s[i][j]=='S'){
                    ss[0]=i;
                    ee[0]=j;
                }
                if(s[i][j]>='0' && s[i][j]<='9'){
                    ss[s[i][j]-'0'] = i;
                    ee[s[i][j]-'0'] = j;
                }
            }
        }
        // for(int i=1;i<=n;i++){
        //     cout<<ss[i]<<" "<<ee[i]<<endl;
        // }
        int ans= 0;
        for(int i=0;i<n;i++){
            dea();
            q.push(node (ss[i],ee[i]));
            d[ss[i]][ee[i]] = 0;
            bfs(ss[i],ee[i],ss[i+1],ee[i+1]);
            ans += d[ss[i+1]][ee[i+1]];
        }
        printf("%d\n",ans);
    }
}

C++: #include<iostream>
#include<cstdio>
#include<string.h>


const int INF = -1;

using namespace std;

char maze[1010][1010];
int H, W, N;
int d[1010][1010];
int dx[4] = { 0,0,1,-1 }, dy[4] = { 1, -1, 0, 0 };
int sx[10], sy[10];
int ans = 0;

struct QNode
{
	int data_sx[1010];
	int data_sy[1010];
	int front, rear;
	int maxsize;
};
typedef struct QNode *Queue;

Queue Create()
{
	Queue Q;
	Q = (Queue)malloc(sizeof(struct QNode));
	Q->front = Q->rear = 0;
	Q->maxsize = 1010;
	return Q;
}
void push(Queue Q,int x,int y)
{
	if ((Q->rear + 1) % Q->maxsize == Q->front)
		return;
	Q->rear = (Q->rear + 1) % Q->maxsize;
	Q->data_sx[Q->rear] = x;
	Q->data_sy[Q->rear] = y;
}
int pop1(Queue Q)
{
	if (Q->front == Q->rear)
		return -1;
	Q->front = (Q->front + 1) % Q->maxsize;
	return Q->data_sx[Q->front];
}
int pop2(Queue Q)
{
	return Q->data_sy[Q->front];
}


void bfs(int i)
{
	Queue Q;
	Q = Create();
	memset(d, -1, sizeof(d));
	push(Q, sx[i], sy[i]);
	d[sx[i]][sy[i]] = 0;
	if (i == N)
		return;
	while (Q->front != Q->rear)
	{
		int x = pop1(Q), y = pop2(Q);
		if (x == sx[i + 1] && y == sy[i + 1])
			return;

		for (int j = 0; j < 4; j++)
		{
			int nx = x + dx[j], ny = y + dy[j];
			if (nx >= 0 && nx < H && ny >= 0 && ny < W && d[nx][ny] == INF && maze[nx][ny]!='X')
			{
				push(Q, nx, ny);
				d[nx][ny] = d[x][y] + 1;
			}
		}
	}
}

void solve()
{
	for (int i = 0; i < H; i++)
	{
		for (int j = 0; j < W; j++)
		{
			if (maze[i][j] == 'S')
				sx[0] = i, sy[0] = j;
			else if (maze[i][j] >= '1'&&maze[i][j] <= '9')
				sx[maze[i][j] - '0'] = i, sy[maze[i][j] - '0'] = j;
		}
	}
	for (int i = 0; i < N; i++)
	{
		bfs(i);
		ans += d[sx[i + 1]][sy[i + 1]];
	}
	cout << ans << endl;
}

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

	for (int i = 0; i < H; i++)
		for (int j = 0; j < W; j++)
			cin >> maze[i][j];
	solve();
}