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<stdio.h>
#include<string.h>
#include<algorithm>
#include<queue>

using namespace std;

struct node
{
    int s;
    int x,y;
};

int dir[][2] = {0,1,1,0,0,-1,-1,0};
int vis[1010][1010];
int n,m,k,sx[20],sy[20];

char map[1010][1010];

int bfs(int x,int y,int ex,int ey)
{
    queue<node> q;
    node a,b,d;
    a.x = x;
    a.y = y;
    a.s = 0;
    vis[x][y] = 1;
    q.push(a);
    while(!q.empty())
    {
        b = q.front();
        q.pop();
        if(b.x == ex && b.y == ey)
           {
                return b.s;
           }
        for(int i = 0; i < 4; i++)
        {
            d.x = b.x + dir[i][0];
            d.y = b.y + dir[i][1];
            if(d.x >= 0 && d.x < n && d.y >= 0 && d.y < m && vis[d.x][d.y] == 0)
            {
                if(map[d.x][d.y] >= '1' && map[d.x][d.y] <= '9' || map[d.x][d.y] == '.')
                {
                    vis[d.x][d.y] = 1;
                    d.s = b.s + 1;
                    q.push(d);
                }
            }
        }
    }
}

int main()
{
    while(~scanf("%d%d%d",&n,&m,&k))
    {
        int i,j,t;

        for(i = 0; i < n; i++)
        {
            scanf("%s",map[i]);
            for(j = 0; j < m; j++)
                if(map[i][j] == 'S')
                {
                    sx[0] = i;
                    sy[0] = j;
                    map[i][j] = '.';
                }
        }
        for(i = 0; i < n; i++)
            for(j = 0; j < m; j++)
                if(map[i][j] >= '1' && map[i][j] <= '9')
                {
                    sx[map[i][j]-'0'] = i;
                    sy[map[i][j]-'0'] = j;
                }
        int ans = 0;
        for(i = 1; i <= k; i++)
        {
            memset(vis,0,sizeof(vis));
            ans += bfs(sx[i-1],sy[i-1],sx[i],sy[i]);
        }
        printf("%d\n",ans);
    }
    return 0;
}

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

#define fi first
#define se second
#define x second
#define y first

typedef pair<int,int> pii;

vector<string> in;
int H, W, N;

int search_length(char s, char g) {
	queue<pair<pii, int> > que;
	int vx[] = {1, -1, 0, 0};
	int vy[] = {0, 0, 1, -1};
	for(int i = 0; i < in.size(); i++) {
		for(int j = 0; j < in[i].size(); j++) {
			if(in[i][j] == s) {
				que.push(pair<pii, int>(pii(i, j), 0));
				j = in[i].size();
				i = in.size();
			}
		}
	}
	int visited[1024][1024] = {0};
	while(!que.empty()) {
		pair<pair<int,int>, int> tmp;
		tmp = que.front(); que.pop();
		for(int i = 0; i < 4; i++) {
			int x_, y_;
			x_ = tmp.fi.x + vx[i]; y_ = tmp.fi.y + vy[i];
			if(!(x_ < 0 || (int)in[0].size() <= x_ || y_ < 0 || (int)in.size() <= y_)) {
				if(in[y_][x_] == g) {
					return tmp.se + 1;
				}
				if(!visited[y_][x_] && in[y_][x_] != 'X') {
					visited[y_][x_] = 1;
					que.push(pair<pii,int>(pii(y_, x_), tmp.se + 1));
				}
			}
		}
	}
	cout << "reach" << endl;
	return -1;
}

int main() {
	cin >> H >> W >> N;
	int ret = 0;
	for(int i = 0; i < H; i++) {
		string tmp;
		cin >> tmp;
		in.push_back(tmp);
	}

	for(int i = 0; i < N; i++) {
		char s, g;
		s = i + '0'; g = i + 1 + '0';
		if(i == 0)
			s = 'S';
		ret += search_length(s, g);
	}
	cout << ret << endl;
	return 0;
}

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]=0;
      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++){
      if(num[i][j]!=0){
	color[num[i][j]]="WHITE";
	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]!=0){
	  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;
}