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 <algorithm>
#include <climits>
#include <string>
#include <vector>
#include <cmath>
#include <queue>

using namespace std;

#define rep(i, n) for (int i=0; i<int(n); i++)
#define all(c) (c).begin(), (c).end()

#define MAX_W 1010
#define MAX_H 1010

int H, W, N;
char A[MAX_H][MAX_W];
vector<bool**> global;

pair<int, int> find_char(char c) {
  rep(y, H) {
    rep(x, W) {
      if (A[y][x] == c) return make_pair(x, y);
    }
  }
  return make_pair(-1, -1);
}

bool visited[MAX_W][MAX_H];
int bfs(int start_x, int start_y, int target_x, int target_y) {
  queue<int> q;
  rep(i, W) rep(j, H) visited[j][i] = false;

  q.push(start_x); q.push(start_y); q.push(0);
  while (!q.empty()) {
    int x  = q.front(); q.pop();
    int y  = q.front(); q.pop();
    int dist = q.front(); q.pop();

    char m = A[y][x];
    if (x == target_x && y == target_y) return dist;

    int dx[] = {0, 1, 0, -1};
    int dy[] = {-1, 0, 1, 0};
    rep(i, 4) {
      int tx = x + dx[i];
      int ty = y + dy[i];
      if (tx >= 0 && tx < W && ty >= 0 && ty < H &&
          A[ty][tx] != 'X' && !visited[ty][tx]) {
        q.push(tx);
        q.push(ty);
        q.push(dist + 1);
        visited[ty][tx] = true;
      }
    }
  }
  return INT_MIN;
}

int main() {
  cin >> H >> W >> N;
  rep(i, H) cin >> A[i];

  // ????§???????
  auto pos_s = find_char('S');
  int start_x = pos_s.first;
  int start_y = pos_s.second;

  int ans = 0;
  for (int i=1; i<=N; i++) {
    auto pos = find_char((char)((int)'0'+i));
    int tx = pos.first;
    int ty = pos.second;
    ans += bfs(start_x, start_y, tx, ty);
    start_x = tx;
    start_y = ty;
  }
  cout << ans << "\n";
  return 0;
}

C++: #include <iostream>
#include <stdlib.h> 
#include <queue>
#include <utility>

using namespace std;

typedef struct pair{
    int x;
    int y;
}pair_t;

const int INF = 10000000;

int bfs();

int H,W,N;
char** field;
int** d;


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

int sx, sy;

int main() {
      cin >> H >> W >> N;
      field =(char**) malloc(sizeof(char*)*H);
      d =(int**) malloc(sizeof(int*)*H);
    
      for(int i=0; i<H;i++){
          char* row = (char*)malloc(sizeof(char)*W);
          int* dr = (int*)malloc(sizeof(int)*W);
          cin >> row;
          field[i] = row;
          d[i] = dr;
      }
    
      for(int i=0; i < H; i++){
          for(int j=0; j < W; j++){
    
              if(field[i][j]=='S'){
                  sx = j;
                  sy = i;
                  field[i][j] = '.';
              }
          }
      }

      int result = bfs();
    
      cout << result << endl;

      for(int i=0; i<H; i++){
          free(field[i]);
      }

      free(field);
  

  return 0;
}

void init_d(int x, int y, int n){

    for(int i=0; i<H; i++){
        for(int j=0; j<W; j++){
            d[i][j] = INF;
        }
    }

    d[y][x] = n;
}

void clear(queue<pair_t> &q){
    queue<pair_t> empty;
    swap(q, empty);
}

int bfs(){
    int cheeze = 1;

    queue<pair_t> que;

    pair_t first = {sx, sy};
    que.push(first);
    d[sy][sx] = 0;

    init_d(sx, sy, 0);

    while(que.size()){
NEXT:
        pair_t p = que.front();
        que.pop();

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

            if(0<= nx && nx < W && 0 <= ny && ny < H && field[ny][nx] != 'X' && d[ny][nx] == INF){
                if(field[ny][nx] != '.'){
                    if((int)(field[ny][nx] - '0') == cheeze ){

                        if(cheeze == N){
                            return d[p.y][p.x] + 1;
                        }


                        init_d(nx, ny, d[p.y][p.x] + 1);
                        clear(que);

                        pair_t n = {nx, ny};
                        que.push(n);
                        
                        cheeze++;
                        goto NEXT;
                    }
                }

                pair_t n = {nx, ny};
                d[ny][nx] = d[p.y][p.x] + 1;
                que.push(n);

            }
        }
    }
    return -1;
}

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

struct position{
  int x, y;
};

int h, w, n, ans = 0;
position cheese[10];
char map[1001][1001];
int dx[4] = {0, 1, 0, -1};
int dy[4] = {-1, 0, 1, 0};

int solve(int times)
{
  bool pushed[1001][1001];
  int cost[1001][1001];
  queue<position> candidate;
  for(int i=1;i<=h;i++){
    for(int j=1;j<=w;j++){
      pushed[i][j]=false;
      cost[i][j]=0;
    }
  }
  candidate.push(cheese[times-1]);

  while(!cost[cheese[times].x][cheese[times].y]){
    position now = candidate.front();
    candidate.pop();
    for(int i = 0; i < 4; i++){
      position next={now.x + dx[i], now.y + dy[i]};
      if(0 < next.x && next.x <= h && 0 < next.y && next.y <= w && map[next.x][next.y] == '.' && !pushed[next.x][next.y]){
		cost[next.x][next.y] = cost[now.x][now.y] + 1;
		position in = {next.x, next.y};
		candidate.push(in);
		pushed[next.x][next.y] = true;
      }
    }
  }
  return cost[cheese[times].x][cheese[times].y];
}

int main()
{
  cin >> h >> w >> n;
  for(int i = 1; i <= h; i++){
    for(int j = 1; j <= w; j++){
      char in;
      cin >> in;
      if(in == 'S'){
	cheese[0] = {i, j};
	map[i][j] = '.';
      }
      else if('1' <= in && in <= '9'){
	cheese[in - '0'] = {i, j};
	map[i][j] = '.';
      }
      else{
	map[i][j] = in;
      }
    }
  }

  for(int i = 1; i <= n; i++){
    ans+=solve(i);
  }

  cout<<ans<<endl;
  return 0;
}

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;
}