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 <bits/stdc++.h>

using namespace std;

typedef struct xyt{
	int xx;
	int yy;
	int tt;
}xyt;

int H, W, N, minute = 0;
char area[1001][1001] = {{0}};
bool areab[1001][1001] = {};
bool visit[1001][1001];
int dx[4] = {0,1,0,-1};
int dy[4] = {1,0,-1,0};


void dfs(int x, int y){
	int X, Y, time;
	int HP =1;
	xyt start = {x, y, 0};
	queue <xyt> Q;
	Q.push (start);
	for(int i = 1; i<=1000;i++){
		for(int j = 1; j<= 1000 ;j++){
			visit[j][i]=0;
		}
	}

	while(HP <= N){
		X = Q.front().xx;
		Y = Q.front().yy;
		time = Q.front().tt;
		Q.pop();
		
		//cout << HP << endl;
		for(int i = 0; i <= 4 ;i++){
			int nx = X + dx[i];
			int ny = Y + dy[i];
			//cout << nx <<" " << ny << " " << area[nx][ny] << endl;
			xyt now;
			if(X + dx[i] <= 0 || Y + dy[i] <= 0 || X + dx[i] > W || Y + dy[i] > H)continue;
			if(visit[nx][ny]==1)continue;
			
			if(areab[X + dx[i]][Y + dy[i]] == 0){
				if(area[X + dx[i]][Y + dy[i]] == HP + '0'){
					minute += time + 1;
					while(!Q.empty()){
						Q.pop();
					}
					now.xx = X + dx[i];
					now.yy = Y + dy[i];
					now.tt = 0;
					Q.push (now);
					HP++;
					for(int k = 1; k<=1000;k++){
						for(int l = 1; l<= 1000 ;l++){
							visit[k][l]=0;
						}
					}
					break;
				}else{
					now.xx = X + dx[i];
					now.yy = Y + dy[i];
					now.tt = time + 1;
					Q.push (now);
					visit[X+dx[i]][Y+dy[i]]=1;
				}
			}
		}
	}
	return;
}


int main(){
	cin >> H >> W >> N;
	for(int i = 1; i <= H ;i++){
		for(int j = 1; j <= W ;j++){
			cin >> area[j][i];
			if(area[j][i] == 'X'){
				areab[j][i] = 1;
			}
		}
	}
	for(int i = 1; i <= H ;i++){
		for(int  j = 1; j <= W ;j++){
			if(area[j][i] == 'S'){
				dfs(j, i);
			}
		}
	}
	cout << minute << endl;
	return 0;
}

C++: #include<iostream>
#include<queue>
#include<cstring>
using namespace std;
int m,n;
int maxe=0;
int che=0;
int k;
struct node{
  int x,y;
};
char mape[1111][1111];
int d[1111][1111];
queue<node> q;
int da[]={0,0,1,-1};
int db[]={1,-1,0,0};
void bfs(){
  while(!q.empty()&&che<k){
    node nn;
    int x=q.front().x;
    int y=q.front().y;
    q.pop();
    if(mape[x][y]>='0'&&mape[x][y]<='9'){
      che++;
      maxe+=d[x][y];
    }
    else mape[x][y]='X';
    for(int i=0;i<4;i++)
      if(x+da[i]>=0&&x+da[i]<m&&y+db[i]>=0&&y+db[i]<n&&mape[x+da[i]][y+db[i]]!='X'){
	int w=x+da[i];
	int e=y+db[i];
	d[w][e]=d[x][y]+1;
	nn.x=w;
	nn.y=e;
	q.push(nn);
      }
  }
}
int main(){
  cin>>m>>n>>k;
  while(!q.empty())q.pop();
  node nn;
  memset(d,-1,sizeof(d));
  for(int i=0;i<m;i++)
    for(int j=0;j<n;j++){
      cin>>mape[i][j];
      if(mape[i][j]=='S'){
	nn.x=i;
	nn.y=j;
	d[i][j]=0;
	q.push(nn);
	mape[i][j]='X';
      }
    }
  bfs();
  cout<<maxe<<"\n";
}

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 <queue>
#include <algorithm>
#include <tuple>
#include <cctype>
using namespace std;

typedef tuple<int, int, int> st; // time, x, y
char F[1010][1010];
int H, W, N;
int X[10], Y[10];
int turn = 0;

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

bool isvalid(int x, int y) {
  return 0 <= x && x < H && 0 <= y && y < W && F[x][y] != 'X';
}

bool isgoal(int x, int y) {
  return isvalid(x, y) && x == X[turn+1] && y == Y[turn+1];
}

int main() {
  scanf("%d%d%d", &H, &W, &N);
  for (auto i=0; i<H; i++) {
    for (auto j=0; j<W; j++) {
      scanf(" %c", &F[i][j]);
      if (isdigit(F[i][j])) {
	int temp = (int)F[i][j] - '0';
	X[temp] = i;
	Y[temp] = j;
      } else if (F[i][j] == 'S') {
	X[0] = i;
	Y[0] = j;
      }
    }
  }
  int res = 0;
  for (turn = 0; turn < N; turn++) {
    bool visited[1010][1010];
    fill(&visited[0][0], &visited[0][0]+1010*1010, false);
    queue<st> Q;
    Q.push(make_tuple(0, X[turn], Y[turn]));
    while (!Q.empty()) {
      int time = get<0>(Q.front());
      int x = get<1>(Q.front());
      int y = get<2>(Q.front());
      Q.pop();
      if (isgoal(x, y)) {
	res += time;
	break;
      } else if (!visited[x][y]) {
	// cerr << "visit: (" << x << "," << y << ")" << endl; 
	visited[x][y] = true;
	for (auto k=0; k<4; k++) {
	  int nx = x + dx[k];
	  int ny = y + dy[k];
	  if (isvalid(nx, ny) && !visited[nx][ny]) {
	    Q.push(make_tuple(time+1, nx, ny));
	  }
	}
      }
    }
  }
  printf("%d\n", res);
}