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 <string>
#include <vector>
#include <iterator>
#include <list>
#include <map>
#include <queue>
#include <bitset>
#include <fstream>
#include <cmath>
using namespace std;
typedef long long ll;

class CPoint
{
public:

	int x, y;

	CPoint() : x(0), y(0){};
	CPoint(int ax, int ay) : x(ax), y(ay){};

	bool operator==(const CPoint& obj);
	bool operator!=(const CPoint& obj);
};


class CPoint;

const int MAX_H = 1000;
const int MAX_W = 1000;
const ll  INF	= 1000000000;

char field[MAX_H][MAX_W];
bool used[MAX_H][MAX_W];
ll	 d[MAX_H][MAX_W];
int  H, W, N;

ll getroad(CPoint start, CPoint goal);

int main()
{
	cin>>H>>W>>N;
	vector<CPoint> factorys(N+1);

	for(int i = 0; i < H; i++){
		for(int j = 0; j < W; j++){
			cin>>field[i][j];
			if(field[i][j] != 'X' && field[i][j] != '.'){
				if(field[i][j] == 'S')	factorys[0] = CPoint(i, j);
				else					factorys[field[i][j] - '0'] = CPoint(i, j);
			}
		}
	}

	ll res = 0;
	for(int i = 0; i < N; i++)
		res += getroad(factorys[i], factorys[i+1]);

	cout<<res<<endl;

	cin.sync(); cin.get();
}

ll getroad(CPoint start, CPoint goal)
{
	for(int i = 0; i < H; i++) for(int j = 0; j < W; j++) used[i][j] = false;
	for(int i = 0; i < H; i++) for(int j = 0; j < W; j++) d[i][j] = INF;
	
	d[start.x][start.y] = 0;

	while(true){

		CPoint v(-1, -1);
		for(int i = 0; i< H; i++)
			for(int j = 0; j <W; j++)
				if(!used[i][j] && field[i][j] != 'X' && (v == CPoint(-1,-1) || d[i][j] < d[v.x][v.y])) v = CPoint(i, j);

		if(v == CPoint(-1, -1)) break;

		used[v.x][v.y] = true;

		if(v.y+1 < W  && field[v.x][v.y+1] != 'X') d[v.x][v.y+1] = min(d[v.x][v.y+1], d[v.x][v.y] + 1);
		if(v.y-1 >= 0 && field[v.x][v.y-1] != 'X') d[v.x][v.y-1] = min(d[v.x][v.y-1], d[v.x][v.y] + 1);
		if(v.x+1 < H  && field[v.x+1][v.y] != 'X') d[v.x+1][v.y] = min(d[v.x+1][v.y], d[v.x][v.y] + 1);
		if(v.x-1 >= 0 && field[v.x-1][v.y] != 'X') d[v.x-1][v.y] = min(d[v.x-1][v.y], d[v.x][v.y] + 1);
	}

	return d[goal.x][goal.y];
}


bool CPoint::operator==(const CPoint& obj)
{
	return (x == obj.x && y == obj.y);
}

bool CPoint::operator!=(const CPoint& obj)
{
	return !(*this == obj);
}

C++: //
// Created by yijiezhu on 12/20/16.
//

#include <iostream>
#include <queue>
#include <cstring>

using namespace std;

const int MAX_N = 1001;
char matrix[MAX_N][MAX_N];
bool visited[MAX_N][MAX_N];
int H, W, N, si, sj;
int delta[] = {0, 1, 0, -1, 0};

void solve() {
    int cnt{0};
    for (int ni = 1; ni <= N; ni++) {
        queue<pair<pair<int, int>, int> > que;
        que.push(make_pair(make_pair(si, sj), 0));
        memset(visited, false, sizeof(visited));
        visited[si][sj] = true;
        while(!que.empty()) {
            auto p = que.front();
            que.pop();
            int x = p.first.first, y = p.first.second;
            if (matrix[x][y] == '0' + ni) {
                si = x; sj = y;
                cnt += p.second;
                break;
            }
            for (int q = 0; q < 4; q++) {
                int n_i = x + delta[q], n_j = y + delta[q+1];
                if (n_i < 0 || n_i >= H || n_j < 0 || n_j >= W) continue;
                if (matrix[n_i][n_j] == 'X' || visited[n_i][n_j]) continue;
                que.push(make_pair(make_pair(n_i, n_j), p.second + 1));
                visited[n_i][n_j] = true;
            }
        }
    }
    cout << cnt << endl;
}

int main() {
    cin >> H >> W >> N;
    for (int i = 0; i < H; i++) {
        for (int j = 0; j < W; j++) {
            cin >> matrix[i][j];
            if (matrix[i][j] == 'S') {
                si = i; sj = j;
            }
        }
    }
    solve();
}

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 <iostream>
#include <vector>
#include <queue>

using namespace std;

vector < vector<int> > hyou(1010, vector<int>(1010, -10));
int dh[] = {0, 1, 0, -1};
int dw[] = {1, 0, -1, 0};

typedef pair<int, int> P;
typedef pair<int, P> Q;

int search(int h, int w, int n) {
	int counter = 0;
	queue<Q> que;
	Q p;
	(p.second).first = h;
	(p.second).second = w;
	p.first = 0;
	que.push(p);
	if (hyou[h][w] == 0) {
		hyou[h][w] = -11;
	} else {
		hyou[h][w] = - hyou[h][w];
	}
	while (!que.empty()) {
		Q pp = que.front();
		que.pop();
		bool hantei = false;
		for (int i = 0; i < 4; i++) {
			if (hyou[(pp.second).first+dh[i]][(pp.second).second+dw[i]] >= 0 ) {
				Q pq;
				(pq.second).first = (pp.second).first+dh[i];
				(pq.second).second = (pp.second).second+dw[i];
				pq.first = pp.first+1;
				if (hyou[(pq.second).first][(pq.second).second] == n) {
					counter = pq.first;
					hantei = true;
					break;
				} else {
					if (hyou[(pq.second).first][(pq.second).second] == 0) {
						hyou[(pq.second).first][(pq.second).second] = -11;
					} else if (hyou[(pq.second).first][(pq.second).second] > 0) {
						hyou[(pq.second).first][(pq.second).second] = -hyou[(pq.second).first][(pq.second).second];
					}
				}
				que.push(pq);
			}
		}
		if (hantei) {
			break;
		}
	}
	for (int i = 0; i < 1010; i++) {
		for (int j = 0; j < 1010; j++) {
			if (hyou[i][j] == -11) {
				hyou[i][j] = 0;
			} else if (hyou[i][j] > -10 && hyou[i][j] < 0) {
				hyou[i][j] = -hyou[i][j];
			}
		}
	}
	return counter;
}

int main() {
	int h, w, n;
	cin >> h >> w >> n;
	char c;
	int sh, sw;
	int data[9][2];
	for (int i = 1; i <= h; i++) {
		for (int j = 1; j <= w; j++) {
			cin >> c;
			if (c == '.') {
				hyou[i][j] = 0;
			} else if (c == 'S') {
				hyou[i][j] = 0;
				sh = i;
				sw = j;
			} else if (c == 'X') {
				hyou[i][j] = -10;
			} else {
				int d = c - '0';
				hyou[i][j] = d;
				data[d-1][0] = i;
				data[d-1][1] = j;
			}
		}
	}
	int counter = 0;
	for (int i = 0; i < n; i++) {
		counter += search(sh, sw, i+1);
		sh = data[i][0];
		sw = data[i][1];
	}
	cout << counter << endl;
	return 0;
}