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<vector>
#include<algorithm>
#include<string>
#include<queue>
 
#define mp make_pair
#define f first
#define s second
 
using namespace std;
 
typedef pair<int,int> P;
 
const int dx[4]={1,0,-1,0},dy[4]={0,1,0,-1};
int h,w;
string grid[1000];
int d[1000][1000];
 
void bfs(P S){
 
  queue<P>que;
  que.push(S);
  d[S.f][S.s]=0;
 
  while(!que.empty()){
    P now=que.front();
     
    que.pop();
    for(int i=0;i<4;i++){
      if(0<=now.f+dx[i] && 0<=now.s+dy[i] &&
     now.f+dx[i]<h && now.s+dy[i]<w
     && grid[now.f+dx[i]][now.s+dy[i]]!='X'){
 
    if(d[now.f][now.s]+1<d[now.f+dx[i]][now.s+dy[i]]){
      d[now.f+dx[i]][now.s+dy[i]]=d[now.f][now.s]+1;
      que.push(P(now.f+dx[i],now.s+dy[i]));
    }
      }
    }
  }
}
 
int main(void){
  int n;
  P v[1001];
 
  cin >> h >> w >> n;
 
  for(int i=0;i<h;i++)cin >> grid[i];
 
  for(int i=0;i<h;i++){
    for(int j=0;j<w;j++){
      if(grid[i][j]=='S')v[0]=mp(i,j);
      if(grid[i][j]!='X'&&grid[i][j]!='.')
    v[grid[i][j]-'0']=mp(i,j);
    }
  }
 
  int ans=0;
  for(int i=0;i<n;i++){
    for(int j=0;j<h;j++)
      for(int k=0;k<w;k++)d[j][k]=100000000;
    bfs(v[i]);
    ans+=d[v[i+1].f][v[i+1].s];
  }
 
  cout << ans << endl;
 
  return 0;
}

C++: #include <cstdio>
#include <vector>

const int MAX_SIZE = 1000;
char field[MAX_SIZE + 1][MAX_SIZE + 1];

const int STEP_NUM = 4;
const int STEP[STEP_NUM][STEP_NUM] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};

using Position = std::pair<int,int>;

const int MAXN = 10;
Position locations[MAXN];
 
int H, W, N;

int get_shortest_distance(int current_HP)
{
	int sx = locations[current_HP-1].first;
	int sy = locations[current_HP-1].second;
	int ex = locations[current_HP].first;
	int ey = locations[current_HP].second;

	bool is_visit[MAX_SIZE + 1][MAX_SIZE + 1]={};
	is_visit[sx][sy]=true;

	std::vector<Position> frontier;
	frontier.push_back(Position{sx,sy});
	for(int step=0;step<W*H;step++)
	{
		std::vector<Position> next_frontier;
		for(auto p:frontier)
			for(int i=0;i<STEP_NUM;i++)
			{
				int nx = p.first+STEP[i][0];
				int ny = p.second+STEP[i][1];
				if(nx==ex && ny==ey)	return step+1;
				if(nx<0 || H<=nx) 		continue;
				if(ny<0 || W<=ny) 		continue;
				if(field[nx][ny]=='X') 	continue;
				if(is_visit[nx][ny]) 	continue;
				next_frontier.push_back(std::make_pair(nx,ny));
				is_visit[nx][ny] = true;
			}
		frontier = next_frontier;
	}
	return -1;
}

int solve()
{
	int total_step = 0;
	for(int i=1;i<N+1;i++)
		total_step += get_shortest_distance(i);
	return total_step;
}

int main()
{
	scanf("%d %d %d", &H, &W, &N);
	for(int i=0; i<H; i++)
		scanf("%s", field[i]);
	for(int i=0; i<H; i++)
		for(int j=0; j<W; j++)
		{
			if(field[i][j]=='S')
				locations[0] = std::make_pair(i,j);
			if(isdigit(field[i][j]))
				locations[field[i][j]-'0'] = std::make_pair(i,j);
		}
	printf("%d\n", solve());
	return 0;
}

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

int h,w,n;
int en;//energy indicates which cheese to eat next
const int MAX_N=1000;
char map[MAX_N][MAX_N];
struct point{
    int x,y;
    int step;
    point(int xx, int yy, int ss){
        x=xx;
        y=yy;
        step=ss;
    }
};
struct point p[10];
int dx[4]={-1,0,1,0}, dy[4]={0,1,0,-1};

int ok(int x, int y){
    if(x>=0 && x<h && y>=0 && y<w) return 1;
    return 0;
}

int bfs(int next){
    int nextcheese = next +1; int res=0;
    
    queue<point> q;
    point cur(p[next].x, p[next].y,0);
    q.push(cur);
    while(q.size()){
        cur = q.front(); q.pop(); 
        int x=cur.x, y=cur.y;
        int nx, ny;
        for(int i=0; i<4; i++){
            nx = x+dx[i]; ny=y+dy[i];
            if(ok(nx, ny)){
                if((map[nx][ny]-'0')==nextcheese) return ++cur.step;
                if(map[nx][ny]=='.'){
                    point temp(nx, ny, cur.step+1);
                    q.push(temp);
                }
            }
        }
    }
}

void solve(){
    int sx, sy;
    scanf("%d%d%d", &h, &w, &n);
    for(int i=0; i<h; i++){
        for(int j=0; j<w; j++){
            char ch;
            cin>>ch; map[i][j]=ch;
            switch(ch){
                case '.': break;
                case 'X': break;
                case 'S': p[0].x = i; p[0].y = j; break;
                default:
                int t=ch-'0';
                p[t].x = i; p[t].y = j;
            }
        }
    }
    int step=0;
    for(int i=0; i<n; i++){
        step+=bfs(i);
    }
    printf("%d\n", step);
}


int main(){
    solve();
}

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

int h, w, n;
vector<vector<bool>> mp;
vector<pair<int,int>> f;

int bfs(pair<int,int> start, pair<int,int> end){
	queue<pair<int, pair<int,int>>> q;
	q.push(make_pair(0, start));
	while(q.size()){
		int c = q.front().first;
		pair<int,int> p = q.front().second;
		q.pop();
		if(p == end) return c;
		int x = p.first;
		int y = p.second;
		for(int dx = -1; dx <= 1; dx++){
			for(int dy = -1; dy <= 1; dy++){
				if((!!dx ^ !!dy) && 0 <= x+dx && x+dx < w && 0 <= y+dy && y+dy < h && !mp[x+dx][y+dy]){
					q.push(make_pair(c+1, make_pair(x+dx, y+dy)));
				}
			}
		}
	}
	return -1;
}

int main(){
	cin >> h >> w >> n;
	mp.assign(w, vector<bool>(h, false));
	f.assign(n+1, make_pair(0, 0));
	for(int y = 0; y < h; y++){
		for(int x = 0; x < w; x++){
			char a;
			cin >> a;
			if(a == 'X') mp[x][y] = true;
			if(a == 'S') f[0] = make_pair(x, y);
			if('1' <= a && a <= '9') f[a - '0'] = make_pair(x, y);
		}
	}
	int ans = 0;
	for(int i = 1; i <= n; i++){
		ans += bfs(f[i-1], f[i]);
	}
	cout << ans << endl;
	return 0;
}