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 <cstdio>
#include <cstring>

char map[1000][1000];
int h,w,res;

void dfs(int x, int y, char c) {
    if(x<0 || y<0 || x>=w || y>=h) return;
    if(map[y][x] == c) {
        map[y][x] = '.';
        dfs(x-1,y,c); dfs(x,y-1,c);
        dfs(x+1,y,c); dfs(x,y+1,c);
    }
}

int main(void) {
    while(true) {
        res = 0;
        memset(map, 0, sizeof(map));

        scanf("%d%d",&h,&w);
        if(!h && !w) break;
        for(int i=0; i<h; i++) scanf("%s",map[i]);

        for(int i=0; i<h; i++)
            for(int j=0; j<w; j++)
                if(map[i][j] != '.') {
                    res++;
                    dfs(j, i, map[i][j]);
                }
        printf("%d\n", res);

    }
    return 0;
}

C++: #include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <queue>

using namespace std;
typedef pair<int, int> pii;

#define S 'S'
#define X 'X'

#define W_MAX 1000

char map[W_MAX][W_MAX];

int main(){
  int H, W, N;
  cin >> H >> W >> N;

  pii pos; //rat position

  for(int i=0; i<H; i++){
    getchar();
    for(int j=0; j<W; j++){
      scanf("%c", &map[i][j]);
      if(map[i][j]==S){
	pos = make_pair(i,j);
      }
    }
  }

  int dx[] = {0, -1, 0 ,1}; int dy[] = {-1, 0, 1, 0};

  int ans=0;

  int next = 1; //next target num
  bool visited[W_MAX][W_MAX];

  while(next <= N){
    memset(visited, false, sizeof(visited));

    queue<pair<pii, int> > q; //<pos, depth>
    q.push(make_pair(pos, 0));

    while(true){
      pair<pii, int> p = q.front(); q.pop();
      bool found = false;
      visited[p.first.first][p.first.second] = true;
      for(int i=0; i<4; i++){
	int nx = p.first.first + dx[i], ny=p.first.second + dy[i];
	if(nx>=0 && nx<H && ny>=0 && ny<W){
	  if(visited[nx][ny]){
	    continue;
	  } else if(map[nx][ny] == '0' + next){
	    found = true;
	    pos = make_pair(nx, ny);
	    break;
	  } else if(map[nx][ny] != X && map[nx][ny] != S){
	    q.push(make_pair(make_pair(nx, ny), p.second+1));
	  }
	}
      }
      if(found){
	ans += p.second+1;
	next++;
	break;
      }
    }
  }

  cout << ans << endl;

}

C++: #include <cstdio>
#include <iostream>
#include <queue>
#include <tuple>

#define MAX_W 1010
#define MAX_H 1010

using namespace std;

int w, h, n;
char sections[MAX_H][MAX_W];
bool visited[MAX_H][MAX_W];
int dx[] = {1, 0, -1, 0};
int dy[] = {0, -1, 0, 1};


int main() {
  scanf("%d %d %d", &h, &w, &n);
  for (int i = 0; i < h; ++i) {
    scanf("%s", sections[i]);
  }

  int sx, sy;
  for (int i = 0; i < h; ++i) {
    for (int j = 0; j < w; ++j) {
      if (sections[i][j] == 'S') {
        sx = j; sy = i;
      }
    }
  }

  int ans = 0;
  queue<tuple<int, int, int> > que;
  que.push(make_tuple(sx, sy, 0));
  for (int hp = 1; hp <= n; ++hp) {
    for (int i = 0; i < h; ++i) {
      for (int j = 0; j < w; ++j) {
        visited[i][j] = false;
      }
    }

    tuple<int, int, int> res;
    while (!que.empty()) {
      int x, y, d;
      tie(x, y, d) = que.front(); que.pop();
      visited[y][x] = true;
      for (int i = 0; i < 4; ++i) {
        int nx = x + dx[i], ny = y + dy[i];
        if ((0 <= nx && nx < w && 0 <= ny && ny < h) &&
            (!visited[ny][nx] && sections[ny][nx] != 'X')) {
          if (sections[ny][nx] == ('0' + hp)) {
            visited[ny][nx] = true;
            res = make_tuple(nx, ny, d + 1);
          }
          else {
            visited[ny][nx] = true;
            que.push(make_tuple(nx, ny, d + 1));
          }
        }
      }
    }

    int x, y, d;
    tie(x, y, d) = res;
    ans += d;
    que = queue<tuple<int, int, int> >();
    que.push(make_tuple(x, y, 0));
  }
  printf("%d\n", ans);
  
  return 0;
}

C++: #include <stdio.h>
#include <queue>
using namespace std;
int d[1000][1000], sx, sy;
char s[1000][1000];
int h,w,n;
int k, l;

int bfs(int,int,int,int);

int main(){
  int result = 0;
  int x[10], y[10], v;
  scanf("%d %d %d", &h, &w, &n);
  for(k = 0 ; k < h ; k++){
      scanf("%s",s[k]);javascript:void(0)
    }
  for( k = 0 ; k < h ; k++ ){
    for( l = 0 ; l < w ; l++){
      if(s[k][l] == 'S'){
	x[0] = l; y[0] = k;
      }
      if('1' <= s[k][l] && s[k][l] <= '9'){
	v = s[k][l]-'1'+1;
	x[v] = l; y[v] = k;
      }
    }
  }
  for (k = 1 ; k <= n ; k++){
   
    result += bfs(x[k-1],y[k-1],x[k],y[k]);
  }
  printf("%d\n", result);
  return 0;
}

int bfs(int sx, int sy, int gx, int gy){
  queue<int> Q;
  int i, j;
  int dx[4]={0, 1, 0, -1};
  int dy[4]={1, 0, -1, 0};
  

  for( i =  0 ; i < h ; i++ ){
    for( j = 0 ; j < w ; j++ ){
      d[i][j] = 100000;
    }
  }

  Q.push(sy*w+sx);
  d[sy][sx]=0; /*スタート地点の初期化*/

  while( !Q.empty() ){
    int u = Q.front(); Q.pop();
    int pi = u/w;
    int pj = u%w;
    if( pi == gy && pj == gx )return d[gy][gx];
    for ( int r = 0; r < 4; r++ ){
      int ni = pi + dy[r];
      int nj = pj + dx[r];
      if ( ni < 0 || nj < 0 || ni >= h || nj >= w ) continue;
      if ( s[ni][nj] == 'X' ) continue;
      if( d[ni][nj] > d[pi][pj]+1 ){
      d[ni][nj] = d[pi][pj] + 1;
      Q.push( ni * w + nj );
      }

    }


  }
  //  printf("%d\n",u);
  return -1;
}

C++: // 各番号間の最短距離をBFSで算出して合計する

#include <bits/stdc++.h>

using namespace std;

struct P
{
  int x;
  int y;
};

int const INF = 1000000;

int N, M, L;

vector<int> dx = {-1, 1, 0, 0};
vector<int> dy = {0, 0, -1, 1};

// 分かりにくいけど破壊的に現在を変更していく
// 順々にチーズを食べてくいくことを表現するため
int bfs(vector<vector<char>> field, P &current, char end)
{
  vector<vector<int>> d(N, vector<int>(M, INF));

  queue<P> q;
  q.push(current);

  d.at(current.x).at(current.y) = 0;

  while (q.size())
  {
    P p = q.front();
    q.pop();

    // 現在位置の更新
    current.x = p.x;
    current.y = p.y;

    if (field.at(p.x).at(p.y) == end)
      break;

    // 四方を探索
    for (int i = 0; i < 4; i++)
    {
      int nx = p.x + dx.at(i);
      int ny = p.y + dy.at(i);      

      // 範囲内
      if (0 <= nx && nx < N && 0 <= ny && ny < M)
      {        
        // 障害物でない、かつ未訪問
        if (field.at(nx).at(ny) != 'X' && d.at(nx).at(ny) == INF)
        {          
          d.at(nx).at(ny) = d.at(p.x).at(p.y) + 1;
          q.push(P{nx, ny});
        }
      }
    }
  }

  return d.at(current.x).at(current.y);
}

string cheese = "123456789";

int main()
{
  P start = P{0, 0};

  cin >> N >> M >> L;

  vector<vector<char>> field(N, vector<char>(M));

  for (int i = 0; i < N; i++)
  {
    for (int j = 0; j < M; j++)
    {
      cin >> field.at(i).at(j);

      if (field.at(i).at(j) == 'S')
        start = P{i, j};
    }
  }

  int count = 0;

  for (int i = 0; i < L; i++)
  {
    count += bfs(field, start, cheese.at(i));
  }
  cout << count << endl;
}