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>
#include <cstring>
using namespace std;

class State{
public:
  int x, y, cost;

  State(int _x, int _y, int _cost){
    x = _x;
    y = _y;
    cost = _cost;
  }
};

int h, w, n;
int cx[12], cy[12];
int dx[] = {1, -1, 0, 0};
int dy[] = {0, 0, 1, -1};
bool closed[1002][1002];
char t[1002][1002];

int bfs(int sx, int sy, int gx, int gy){
  queue<State> open;
  open.push(State(sx, sy, 0));
  memset(closed, 0, sizeof(closed));

  while(!open.empty()){
    State st = open.front();
    open.pop();

    if(closed[st.y][st.x]) continue;
    closed[st.y][st.x] = true;

    if(st.x == gx && st.y == gy){
      return st.cost;
    }

    for(int i = 0; i < 4; i++){
      int nx = st.x + dx[i];
      int ny = st.y + dy[i];

      if(0 <= nx && nx < w && 0 <= ny && ny < h && t[ny][nx] == '.'){
        open.push(State(nx, ny, st.cost + 1));
      }
    }
  }

  return 99999999;
}

int main(){
  while(cin >> h >> w >> n){
    for(int i = 0; i < h; i++){
      cin >> t[i];

      for(int j = 0; j < w; j++){
        if(t[i][j] == 'S'){
          cx[0] = j;
          cy[0] = i;
          t[i][j] = '.';
        }
        else if('0' <= t[i][j] && t[i][j] <= '9'){
          int idx = t[i][j] - '0';
          cx[idx] = j;
          cy[idx] = i;
          t[i][j] = '.';
        }
      }
    }

    int ans = 0;

    for(int i = 1; i <= n; i++){
      ans += bfs(cx[i - 1], cy[i - 1], cx[i], cy[i]);
    }

    cout << ans << endl;
  }
}

C++: #include <iostream>
#include <iomanip>
#include <queue>


#define REP(i,a,b) for(int i=a;i<b;i++)
#define rep(i,n) REP(i,0,n)

#define HMAX 1000
#define WMAX 1000
#define NMAX 9
#define INF 10000000
#define EMPTY -1
#define OBSTACLE -2

int H, W, N;
int map[HMAX + 2][WMAX + 2];

int dirs_h[] = {0, 0, 1, -1};
int dirs_w[] = {1, -1, 0, 0};

struct Position {
	int h;
	int w;
};
Position factory[NMAX + 1];
Position dirs[4] = {
	Position{ 0,  1},
	Position{ 0, -1},
	Position{ 1,  0},
	Position{-1,  0}
};

using namespace std;

int go(Position start, Position end) {
	queue<Position> q;
	q.push(start);

	map[start.h][start.w] = 0;
	int min = 0;
	while (!q.empty()) {
		Position pos = q.front();

		q.pop();
		
		rep(i, 4){
			Position pos_n = Position{pos.h + dirs[i].h, pos.w + dirs[i].w};

			if (map[pos_n.h][pos_n.w] != OBSTACLE) {
				if (map[pos_n.h][pos_n.w] == EMPTY) {
					q.push(pos_n);
				}else{
					if (min > map[pos_n.h][pos_n.w] + 1)
						min = map[pos_n.h][pos_n.w] + 1;
				}
			}
		}
		map[pos.h][pos.w] = min;
		min = INF;
		if (pos.h == end.h && pos.w == end.w)
			break;
	}
	int ans = map[end.h][end.w];

	rep(i, H + 2){
		rep(j, W + 2){
			/*debug
			switch(map[i][j]){
				case OBSTACLE:
					cout << "  X";
				break;
				case EMPTY:
					cout << "   ";
				break;
				default:
					cout << setw(3) << map[i][j];
				break;
			}*/
			
			map[i][j] = map[i][j] >= 0 ? EMPTY : map[i][j];
		}
		//cout << endl;
	}
	return ans;
}

int main() {
	scanf("%d%d%d", &H, &W, &N);
	
	rep(i, H){
		rep(j, W){
			char m;
			scanf(" %c",&m);
			int m_i = m - '0';
			switch (m) {
				case 'S':
					factory[0] = Position{i + 1, j + 1};
					map[i + 1][j + 1] = EMPTY;
				break;
				case 'X':
					map[i + 1][j + 1] = OBSTACLE;
				break;
				case '.':
					map[i + 1][j + 1] = EMPTY;
				break;
				default:
					int num = m - '0';
					factory[num] = Position{i + 1, j + 1};
					map[i + 1][j + 1] = EMPTY;
				break;
			}
		}
	}

	rep(i, H + 2){
		map[i][0] = OBSTACLE;
		map[i][W + 1] = OBSTACLE;
	}

	rep(j, W + 2){
		map[0][j] = OBSTACLE;
		map[H + 1][j] = OBSTACLE;
	}

	int sum = 0;
	rep(i, N)
		sum += go(factory[i], factory[i + 1]);

	cout << sum << endl;
}

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

const int INF=100000000;
typedef pair<int, int> P;

int n,h,w;
char maze[1111][1111];
int d[1111][1111];
int dx[4]={1,0,-1,0};
int dy[4]={0,1,0,-1};
int sy,sx;
int gy,gx;

int bfs();
int main(){

  int cnt=0;
  int num='0';
  char g,s;
  
  
  scanf("%d %d %d",&h,&w,&n);
  for(int i=0;i<h;i++){
    scanf("%s",maze[i]);
    for(int j=0;j<w;j++){
      if(maze[i][j]=='S'){
	sx=i;
	sy=j;
      }
      else if(maze[i][j]=='1'){
	g='1';
	gx=i;
	gy=j;
      }
    }
  }

  cnt+=bfs();
  // printf("%c=%d\n",g,cnt);

  for(int k=1;k<n;k++){
    s=g;
    sx=gx;
    sy=gy;
    g++;
    for(int i=0;i<h;i++){
      for(int j=0;j<w;j++){
	
	if(maze[i][j]==g){
	  gy=j;
	  gx=i;
	  break;
	}
      }
      if(maze[gy][gx]==g) break;
    }
    cnt+=bfs();
    // printf("%c=%d\n",g,cnt);
  }

  printf("%d\n",cnt);
  
  return 0;
}

int bfs(){
  queue<P> que;
  for(int i=0;i<h;i++){
    for(int j=0;j<w;j++){
      d[i][j]=INF;
    }
  }

  que.push(P(sx,sy));
  d[sx][sy]=0;

  while(que.size()){
    P p=que.front();
    que.pop();
    if(p.first==gx && p.second==gy){
      // printf("gx=%d gy=%d\n",gx,gy);
      break;
    }

    for(int i=0;i<4;i++){
      int nx=p.first+dx[i],ny=p.second+dy[i];
      if(0<=nx && nx<h && 0<=ny && ny<w && maze[nx][ny]!='X' && d[nx][ny]==INF){
	que.push(P(nx,ny));
	d[nx][ny]=d[p.first][p.second]+1;
      }
    }

  }
  /*
  for(int i=0;i<h;i++){
    for(int j=0;j<w;j++){
      if(d[i][j]==INF){
	printf("  0");
      }else{
	printf("%3d",d[i][j]);
      }
    }
    printf("\n");
    }*/

  return d[gx][gy];
}