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<queue>
using namespace std;
int H,W,N,sx,sy;
char map[1010][1010];
int dir[4][2]={{-1,0},{0,1},{1,0},{0,-1}};
struct Point
{
    int x,y,num,energy,step;
} ;
int BFS()
{
    int ans=1000000;
    queue<Point> q;
    Point p1,p2;
    p1.x=sx;p1.y=sy;p1.num=0;p1.energy=1;p1.step=0;
    q.push(p1);
    while(!q.empty())
    {
       p1=q.front();
       q.pop();
//cout<<p1.x<<" "<<p1.y<<" "<<p1.num<<" "<<p1.step<<" "<<p1.energy<<endl;
       if(p1.num==N&&ans>p1.step)
       {
           ans=p1.step;
           break;
       }

       for(int i=0;i<4;i++)
       {
         p2.x=p1.x+dir[i][0];
         p2.y=p1.y+dir[i][1];
         p2.num=p1.num;
         p2.energy=p1.energy;
         p2.step=p1.step+1;
         if(p2.x<0||p2.x>=H||p2.y<0||p2.y>=W)continue;
         if(map[p2.x][p2.y]=='X') continue;
         else if(map[p2.x][p2.y]=='.')
            {
                q.push(p2);
               // cout<<p2.x<<" "<<p2.y<<endl;
            }
         else if(p2.energy>=(map[p2.x][p2.y]-48))
         {
             p2.num++;p2.energy++;
             map[p2.x][p2.y]='.';
             q.push(p2);
            // cout<<p2.x<<" "<<p2.y<<endl;
         }
       }
    }
return ans;
}
int main()
{
    while(cin>>H>>W>>N)
   {
    for(int i=0;i<H;i++)
     for(int j=0;j<W;j++)
     {
         cin>>map[i][j];
         if(map[i][j]=='S')
         {
             sx=i;sy=j;
         }
     }
    cout<<BFS()<<endl;
  }
}

C++: #include<cstdio>
#include<cstring>
#include<iostream>
#include<queue>
#include<vector>
#include<algorithm>
#include<string>
#include<cmath>
#include<set>
#include<map>
#include<vector>
#include<stack>
#include<utility>
#include<sstream>
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const int maxn = 1005;
int a[1005][1005];
int x[20], y[20];
int ans, w, h, n;
bool leap[1005][1005];
int dir[4][2] = { 1, 0, -1, 0, 0, 1, 0, -1 };
struct Node
{
	int x, y, t;
	Node(int x, int y, int t) :x(x), y(y), t(t){}
};
int work(int xx, int yy, int pos)
{
	memset(leap, false, sizeof(leap));
	leap[xx][yy] = 1;
	queue<Node>p;
	p.push(Node(xx, yy, 0));
	while (p.size())
	{
		Node temp = p.front();
		p.pop();
		for (int i = 0; i < 4; i++)
		{
			int tempx = temp.x + dir[i][0];
			int tempy = temp.y + dir[i][1];
			if (tempx >= 1 && tempx <= h&&tempy >= 1 && tempy <= w)
			{
				if (a[tempx][tempy] == 1)continue;
				if (leap[tempx][tempy] == 1)continue;
				if (tempx == x[pos + 1] && tempy == y[pos + 1])
				{
					return temp.t + 1;
				}
				leap[tempx][tempy] = 1;
				p.push(Node(tempx, tempy, temp.t + 1));
			}
		}
	}

}
int main()
{
#ifdef LOCAL
	freopen("C:\\Users\\ΡΡ\\Desktop\\in.txt", "r", stdin);
	//freopen("C:\\Users\\ΡΡ\\Desktop\\out.txt","w",stdout);
#endif // LOCAL
	while (scanf("%d%d%d", &h, &w, &n) != EOF)
	{
		char s[1005];
		for (int i = 1; i <= h; i++)
		{
			scanf("%s", s);
			for (int j = 1; j <= w; j++)
			{
				if (s[j - 1] == '.')
					a[i][j] = 0;
				else if (s[j - 1] == 'X')
					a[i][j] = 1;
				else if (s[j - 1] == 'S')
				{
					x[0] = i; y[0] = j;
					a[i][j] = 0;
				}
				else
				{
					a[i][j] = 0;
					int id = s[j - 1] - '0';
					x[id] = i; y[id] = j;
				}
			}
		}
		ans = 0;
		for (int i = 0; i < n; i++)
		{
			ans = ans + work(x[i], y[i], i);
		}
		printf("%d\n", ans);
	}
	return 0;
}

C++: #include <iostream>
#include <queue>
#include <unordered_map>
#include <utility>
#include <array>
#include <cstring>

bool isObstacle[1000][1000];
bool done[1000][1000];

int main() {
	int h, w, n;
	std::cin >> h >> w >> n;

	std::unordered_map<int, int> factories;

	for (int i = 0; i < h; ++i) {
		for (int j = 0; j < w; ++j) {
			char c;
			std::cin >> c;

			if (c == 'S')
				factories[0] = j * 1000 + i;
			else if ('1' <= c && c <= '9')
				factories[c - '0'] = j * 1000 + i;
			else if (c == 'X')
				isObstacle[j][i] = true;
		}
	}

	int ans = 0;
	for (int i = 0; i < n; ++i) {
		const int sx = factories[i] / 1000, sy = factories[i] % 1000;
		const int gx = factories[i + 1] / 1000, gy = factories[i + 1] % 1000;

		std::memset(done, 0, sizeof(done));

		done[sx][sy] = true;

		auto candidate = [h, w](int x, int y) {
			std::array<int, 4> arr;
			arr[0] = ((x == 0 || isObstacle[x - 1][y] || done[x - 1][y]) ? -1 : (done[x - 1][y] = true, (x - 1) * 1000 + y));
			arr[1] = ((x == w - 1 || isObstacle[x + 1][y] || done[x + 1][y]) ? -1 : (done[x + 1][y] = true, (x + 1) * 1000 + y));
			arr[2] = ((y == 0 || isObstacle[x][y - 1] || done[x][y - 1]) ? -1 : (done[x][y - 1] = true, x * 1000 + y - 1));
			arr[3] = ((y == h - 1 || isObstacle[x][y + 1] || done[x][y + 1]) ? -1 : (done[x][y + 1] = true, x * 1000 + y + 1));

			return std::move(arr);
		};

		std::queue<std::pair<int, int>> q;
		q.push({ factories[i], 0 });
		while (!q.empty()) {
			const auto& top = q.front();
			const int nx = top.first / 1000, ny = top.first % 1000;
			int cost = top.second;

			auto&& c = candidate(nx, ny);
			for (auto v : c) {
				if (v != -1) {
					if (v / 1000 == gx && v % 1000 == gy) {
						ans += cost + 1;
						q.pop();
						goto end;
					}
					q.push({ v, cost + 1 });
				}
			}

			q.pop();
		}
	end:;
	}

	std::cout << ans << std::endl;
}

C++: #include <queue>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;
char e[1005][1005];
int dx[4] = {0,0,-1,1};
int dy[4] = {1,-1,0,0};
int h, w, n;
int stx, sty;
int countn,k;

struct edge {
	int tx, ty;
	int step;
};

int book[1005][1005]; 
edge a[15];
void bfs( int x, int y ) {
	queue<edge> qq;
	book[x][y] = 1;
	edge ee;
	 ee.tx = x;
	 ee.ty = y;
	 ee.step = 0;
	qq.push( ee );
	while( !qq.empty() ) {
		edge temp = qq.front();
		qq.pop();
		if( temp.tx == a[k].tx && temp.ty == a[k].ty ){
			k++;
			countn += temp.step;
			if(k>n) return;
			while (!qq.empty()) qq.pop();
			
			memset(book,0,sizeof(book));
			bfs( temp.tx, temp.ty );
			return ;
		}
		for( int i = 0; i < 4; i++ ) {
			int ttx = temp.tx + dx[i];
			int tty = temp.ty + dy[i];
			if(ttx<=0 || tty<=0 || ttx>h || tty>w ) continue;
			if(e[ttx][tty] != 'X' && book[ttx][tty]==0) {
				book[ttx][tty] =1;
				edge tt;
				tt.tx = ttx;
				tt.ty = tty;
				tt.step = temp.step+1;
				qq.push(tt);
			}
		}
	}
	return ;
}

int main() {
	
	cin>>h>>w>>n;
	for( int i = 1; i <= h; i++ ) {
		
		getchar();
		for( int j = 1; j <= w; j++ ) {
			scanf("%c", &e[i][j] );
			if( e[i][j] == 'S' ) stx = i, sty = j;
			if(e[i][j]>='1' && e[i][j]<='9')a[e[i][j]-'0'].tx = i,a[e[i][j]-'0'].ty = j;
		}
	}
	countn = 0;
	k=1;
	bfs(stx,sty); 
	
	cout<<countn<<endl; 
	
}