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 <queue>
#include <algorithm>

using namespace std;

int H, W, N;
typedef pair<int, int> coord;

struct data {
  int y, x, cost, dist;

  bool operator >(const data &e) const{
    return cost > e.cost;
  }
};

bool isInside( int y, int x ){
  return ( 0 <= y && y < H && 0 <= x && x < W );
}

int main(){

  cin >> H >> W >> N;

  vector< vector<char> > field(H, vector<char>(W));
  vector<coord> coord_list(N+1);
  int sy, sx, gy, gx;

  for(int y = 0; y < H; y++){
    for(int x = 0; x < W; x++){
      cin >> field[y][x];

      if( field[y][x] != 'S' && field[y][x] != '.' ){
        coord_list[field[y][x] - '0'] = coord(y,x);
      }else if( field[y][x] == 'S' ){
        sy = y;
        sx = x;
      }
    }
  }

  int answer = 0;
  int x, y;

  for(int i = 1; i <= N; i++){
    gy = coord_list[i].first;
    gx = coord_list[i].second;

    priority_queue<data, vector<data>, greater<data> > que;
    vector< vector<bool> > check_field(H, vector<bool>(W));

    data d;
    d.dist = 0;
    d.cost = 0;
    d.y = sy;
    d.x = sx;

    que.push(d);

    while( !que.empty() ){
      d = que.top(); que.pop();
      y = d.y;
      x = d.x;
      check_field[y][x] = true;

      if( d.y == gy && d.x == gx ){
        sy = gy;
        sx = gx;
        answer += d.dist;
        break;
      }
      if( isInside( y, x+1 ) && !check_field[y][x+1] && field[y][x+1] != 'X'){
        data nd;
        nd.y = y;
        nd.x = x+1;
        nd.dist = d.dist + 1;
        nd.cost = nd.dist + abs( gy - nd.y ) + abs( gx - nd.x );
        que.push(nd);
      }
      if( isInside( y+1, x ) && !check_field[y+1][x] && field[y+1][x] != 'X'){
        data nd;
        nd.y = y+1;
        nd.x = x;
        nd.dist = d.dist + 1;
        nd.cost = nd.dist + abs( gy - nd.y ) + abs( gx - nd.x );
        que.push(nd);
      }
      if( isInside( y, x-1 ) && !check_field[y][x-1] && field[y][x-1] != 'X'){
        data nd;
        nd.y = y;
        nd.x = x-1;
        nd.dist = d.dist + 1;
        nd.cost = nd.dist + abs( gy - nd.y ) + abs( gx - nd.x );
        que.push(nd);
      }
      if( isInside( y-1, x ) && !check_field[y-1][x] && field[y-1][x] != 'X'){
        data nd;
        nd.y = y-1;
        nd.x = x;
        nd.dist = d.dist + 1;
        nd.cost = nd.dist + abs( gy - nd.y ) + abs( gx - nd.x );
        que.push(nd);
      }
    }
  }

  cout << answer << endl;
  return 0;
}

C++: #include<cstdio>
#include<queue>
#include<algorithm>
using namespace std;
const int INF = 100000000;
int dx[] = {0,0,1,-1};
int dy[] = {1,-1,0,0};

typedef pair< int, int > point;
int h,w,n;
char map[1002][1002];
int x[10],y[10];
int ans = 0;

int main(){
  scanf("%d %d %d",&h,&w,&n);
  for(int i=0;i<=h+1;i++){
    for(int j=0;j<=w+1;j++){
      if(i==0||j==0||i==h+1||j==w+1) map[i][j] = 'X';
      else scanf(" %c ",&map[i][j]);
      if(map[i][j]=='S'){
        x[0] = i;
        y[0] = j;
        map[i][j] = '.';
      }else if(map[i][j]!='.'&&map[i][j]!='X'){
        x[map[i][j]-48] = i;
        y[map[i][j]-48] = j;
        map[i][j] = '.';
      }
    }
  }
  for(int i=0;i<n;i++){
    queue<point> q;
    int d[1002][1002];
    fill(d[0],d[0]+1002*1002,INF);
    d[x[i]][y[i]] = 0;
    q.push(point(x[i],y[i]));
    while(true){
      point np = q.front();
      q.pop();
      int nx = np.first;
      int ny = np.second;
      if(nx==x[i+1]&&ny==y[i+1]){
        ans+=d[nx][ny];
        break;
      }
      for(int j=0;j<4;j++){
        if(map[nx+dx[j]][ny+dy[j]]=='.'){
          if(d[nx+dx[j]][ny+dy[j]]>d[nx][ny]+1){
            d[nx+dx[j]][ny+dy[j]] = d[nx][ny]+1;
            q.push(point(nx+dx[j],ny+dy[j]));
          }
        }
      }
    }
  }
  printf("%d\n",ans);
  return 0;
}

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

typedef pair<int,int> P;
const int INF = 1e+8;
int h, w, n;
char c[1001][1001];
int d[1001][1001];
int dx[4] = {0,0,-1,1};
int dy[4] = {-1,1,0,0};

int bfs(char s){
	int sx, sy, gx, gy;
	for(int y=0 ; y < h ; y++ ){
		for(int x=0 ; x < w ; x++ ){
			d[y][x] = INF;
			if( c[y][x] == 'S' ) c[y][x] = '0';
			if( c[y][x] == s ) sx = x, sy = y;
			if( c[y][x] == s+1 ) gx = x, gy = y;
		}
	}
	d[sy][sx] = 0;
	queue<P> q;
	q.push( P(sx,sy) );
	int res = INF;
	while( !q.empty() ){
		int x = q.front().first;
		int y = q.front().second;
		q.pop();
		
		if( x == gx && y == gy ){
			res = d[y][x];
			break;
		}
		for(int i= 0 ; i < 4 ; i++ ){
			int mx = x + dx[i];
			int my = y + dy[i];
			if( mx < 0 || my < 0 || w <= mx || h <= my ) continue;
			if( c[my][mx] == 'X' ) continue;
			
			if( d[my][mx] == INF ){
				d[my][mx] = d[y][x] + 1;
				q.push( P(mx,my) );
			}
		}
	}
	return res;
}

int main(){
	cin >> h >> w >> n;
	for(int y = 0 ; y < h ; y++ ){
		cin >> c[y];
	}
	int ans = 0;
	for(int i=0 ; i < n ; i++ ){
		ans += bfs(i+'0');
	}
	cout << ans << endl;
}

C++: #include <iostream>
#include <queue>
#define N 1002
#define INFINITY 2000000000
using namespace std;
int bfs(char,char);
int h,w,n,num[N][N];
string str[N];
string color[N*N];
int main(){
  int i,j,number,ans;
  cin >> h >> w >> n;
  for(i=0;i<=w+1;i++) str[0]+='X',str[h+1]+='X';
  for(i=1;i<=h;i++){
    cin >> str[i];
    str[i]='X'+str[i]+'X';
  }
  number=1;
  for(i=0;i<=h+1;i++){
    for(j=0;j<=w+1;j++){
      if(str[i][j]=='X') num[i][j]=-1;
      else{
	num[i][j]=number;
	number++;
      }
    }
  }
  ans=bfs('S','1');
  for(i=1;i<n;i++){
    ans+=bfs(i+'0',i+1+'0');
  }
  cout << ans << endl;
  return 0;
}
int bfs(char s,char g){
  queue<int> q;
  int d[N*N],i,j,u,ret;
  for(i=1;i<=h;i++){
    for(j=1;j<=w;j++){
      color[num[i][j]]="WHITE";
      if(num[i][j]!=-1) d[num[i][j]]=INFINITY;
    }
  }
  for(i=1;i<=h;i++){
    for(j=1;j<=w;j++){
      if(str[i][j]==s){
	color[num[i][j]]="GLAY";
	d[num[i][j]]=0;
	q.push(num[i][j]);
      }
    }
  }
  while(q.empty()!=1){
    u=q.front();
    q.pop();
    for(i=1;i<=h;i++){
      for(j=1;j<=w;j++){
	if(num[i][j]!=-1){
	  if((num[i-1][j]==u||num[i+1][j]==u||num[i][j+1]==u||num[i][j-1]==u)&&color[num[i][j]]=="WHITE"){
	    color[num[i][j]]="GLAY";
	    d[num[i][j]]=d[u]+1;
	    q.push(num[i][j]);
	  }
	}
      }
    }
    color[u]="BLACK";
  }
  for(i=1;i<=h;i++){
    for(j=1;j<=w;j++){
      if(str[i][j]==g){
	ret=d[num[i][j]];
      }
    }
  }
  return ret;
}