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 <algorithm>
#define N 1005
#define INFINITY 2000000000
using namespace std;
void bfs();
int h,w,n,num[N][N],d[N],M[N][N],u,m;
string color[N],in[N];
int main(){
  int i,j,k;
  cin >> h >> w >> n;
  for(i=0;i<h+2;i++)
    for(j=0;j<w+2;j++)
      num[i][j]=-1;
  for(i=1;i<=h;i++) cin >> in[i],in[i]='X'+in[i];
  k=0;
  for(i=1;i<=h;i++){
    for(j=1;j<=w;j++){
      if(in[i][j]!='X') num[i][j]=k,k++;
    }
  }
  m=max(h,w);
  for(i=0;i<=m;i++)
    for(j=0;j<=m;j++)
      M[i][j]=0;
  for(i=1;i<=h;i++){
    for(j=1;j<=w;j++){
      if(num[i][j]!=-1&&num[i+1][j]!=-1)
	M[num[i][j]][num[i+1][j]]=M[num[i+1][j]][num[i][j]]=1;
      if(num[i][j]!=-1&&num[i][j+1]!=-1)
	M[num[i][j]][num[i][j+1]]=M[num[i][j+1]][num[i][j]]=1;
    }
  }
  bfs();
  return 0;
}
void bfs(){
  int i,j,p=1,t=0,flag=0,x=1;
  char start='S',goal='1';
  queue<int> q;
  while(1){
    if(flag==1) start=x+'0',goal=x+'0'+1,x++;
    for(i=1;i<=h;i++){
      for(j=1;j<=w;j++){
	color[num[i][j]]="WHITE",d[num[i][j]]=INFINITY;
      }
    }
    for(i=1;i<=h;i++){
      for(j=1;j<=w;j++){
	if(in[i][j]==start) 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(M[u][num[i][j]]&&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(in[i][j]==goal) t+=d[num[i][j]];
      }
    }
    flag=1;
    if(x>n) break;
  }
  cout << t << 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];
int d[N*N],u,ret;
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 i,j;
  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;
}

C++: 


#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<stack>
#include<queue>
#include<vector>
#include<algorithm>
#include<string>
#include<iostream>
#include<set>
#include<map>

using namespace std;
typedef long long ll;
int mod(ll a){
    int c=a%1000000007;
    if(c>=0)return c;
    else return c+1000000007;
}
typedef pair<int,int> i_i;
typedef pair<ll,ll> l_l;
#define inf 100000000/*10^8*/

/////////////////////////////////


struct ball{
    int i,j,count;
};
int h,w,n;
char room[1001][1001];
i_i goal[11];
bool done[1001][1001];

int di[4]={1,0,-1,0};
int dj[4]={0,1,0,-1};

int  dfs(int k){
    for(int i=0;i<=h-1;i++)for(int j=0;j<=w-1;j++)done[i][j]=false;
    int si=goal[k].first,sj=goal[k].second;
    int gi=goal[k+1].first,gj=goal[k+1].second;
    queue<ball> q;
    ball ba;ba.i=si;ba.j=sj;ba.count=1;
    q.push(ba);
    bool whi=true;
    int ans=0;
    while(whi){
        ball pos=q.front();q.pop();
        done[pos.i][pos.j]=true;
        for(int i=0;i<=3;i++){
            int ii=pos.i+di[i],jj=pos.j+dj[i];
            if(0<=ii&&ii<=h-1&&0<=jj&&jj<=w-1&&room[ii][jj]!='X'&&done[ii][jj]==false){
                if(ii==gi&&jj==gj)ans=pos.count,whi=false;
                else{
                    ba.i=ii;ba.j=jj;ba.count=pos.count+1;
                    q.push(ba);
                }
            }
        }
    }
    return ans;
}

int main(){
    cin>>h>>w>>n;
    for(int i=0;i<=h-1;i++)scanf("%s",room[i]);
    for(int i=0;i<=h-1;i++)for(int j=0;j<=w-1;j++){
        if(room[i][j]=='.');
        else if(room[i][j]=='X');
        else if(room[i][j]=='S')goal[0]=make_pair(i,j);
        else goal[room[i][j]-'0']=make_pair(i,j);
    }
    int ans=0;
    for(int i=0;i<=n-1;i++){
        ans+=dfs(i);
    }
    
    cout<<ans<<endl;
    return 0;
}

C++: #include <stdio.h>
#include <stdlib.h>

#include <queue>

using namespace std;

typedef struct State_Def {
	int y;
	int x;
	State_Def(int _y, int _x) {y = _y; x = _x;}
} S;

const int INF = 1e+8;
int h, w, n;
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
char **data;
int **dist;
int *fX;
int *fY;

int bfs(int si, int sj, int gi, int gj)
{
	int res = 0;
	int i, j;
	queue<S> q;
	S s	= S(si, sj);
	q.push(s);

	for (i=0; i<h; i++)
		for (j=0; j<w; j++)
			dist[i][j] = INF;
	dist[si][sj] = 0;

	while (!q.empty()) {
		S t = q.front();
		q.pop();


		if (t.x == gj && t.y == gi) break;

		for (i=0; i<4; i++) {
			int nx = t.x + dx[i];
			int ny = t.y + dy[i];
			if (0<=nx && nx<w && 0<=ny && ny<h && data[ny][nx] != 'X' && dist[ny][nx] == INF) {
				dist[ny][nx] = dist[t.y][t.x] + 1;
				q.push(S(ny, nx));
			}
		}
	}

	return dist[gi][gj];	
}

int main()
{
	int i, j;
	int sI, sJ;	
	int res;

	scanf("%d%d%d ", &h, &w, &n);
	data = (char **)calloc(h, sizeof(char *));;
	for (i=0; i<h; i++)
		data[i] = (char *)calloc(w, sizeof(char));

	fX = (int *)calloc(n+1, sizeof(int));;
	fY = (int *)calloc(n+1, sizeof(int));;

	for (i=0; i<h; i++) {
		for (j=0; j<w; j++)
			scanf("%c ", &(data[i][j]));
	}

	for (i=0; i<h; i++) {
		for (j=0; j<w; j++) {
			if (data[i][j] == 'S') {
				fX[0] = j;  	
				fY[0] = i;  	
			} else if (0 < data[i][j] - '0' && data[i][j] - '0' <= n) {
				fX[ (int)(data[i][j] - '0') ] = j;  	
				fY[ (int)(data[i][j] - '0') ] = i;  	
			}
		}
	}

	dist = (int **)calloc(h, sizeof(int *));;
	for (i=0; i<h; i++) 
		dist[i] = (int *)calloc(w, sizeof(int));

	res = 0;
	for (i=0; i<n; i++) 
		res += bfs(fY[i], fX[i], fY[i+1], fX[i+1]);

	printf("%d\n", res);

	for (i=0; i<h; i++)
		free(data[i]);
	free(data);

	for (i=0; i<h; i++)
		free(dist[i]);
	free(dist);

	free(fX);
	free(fY);

	return 0;
}