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 <queue>
using namespace std;

#define N 1001
int cols,rows,n;
char a[N][N];
bool visited[N][N] = {0};
int minTime;
int direction[4][2] = {{-1,0},{1,0},{0,-1},{0,1}};

struct Point{
	int x;
	int y;
};

bool isInMap(Point p){
	if(p.x < 0 || p.x >= rows)return 0;
	if(p.y < 0 || p.y >= cols)return 0;
	else return 1;
}

int bfs(Point startP,Point endP){
	//printf("strat x = %d y= %d\n",startP.x,startP.y);
	//printf("end x = %d y = %d\n",endP.x,endP.y);
	
	int count = 1;
	queue<Point> point;
	int time =0;
	point.push(startP);
	visited[startP.x][startP.y] = 1;

	while(point.size()){
		int count1 = count;
		//printf("count1 = %d\n",count1);
		count = 0;
		time++;
		for(int i = 0; i < count1; i++)
		{
			//printf("time = %d",time);
			Point cur = point.front();
			
			point.pop();
			for(int j = 0 ; j < 4; j++)
			{
				Point temp;
				temp.x = cur.x + direction[j][0];
				temp.y = cur.y + direction[j][1];
				if(isInMap(temp) && a[temp.x][temp.y] != 'X' && visited[temp.x][temp.y] == 0)
				{
					point.push(temp);
					visited[temp.x][temp.y] = 1;
					count++;
				}
				if(temp.x == endP.x && temp.y == endP.y)return time;
			}
		}
	}


}

int main(){
	Point startP,endP;
	int totalStep = 0;
    scanf("%d%d%d",&rows,&cols,&n);
	getchar();

	for(int i = 0; i < rows; i++)
	{
		for(int j = 0 ; j < cols; j++)
		{
			scanf("%c",&a[i][j]);
			if(a[i][j] == 'S'){a[i][j] = '0';}
		}
		getchar();
	}

	minTime = 100000;
	for(int k = 0; k < n; k++)
	{
		for(int i = 0; i < rows; i++)
			for(int j = 0; j <cols; j++)
			{
				if((int)a[i][j] == (k+48)){startP.x = i;startP.y = j;}
				if((int)a[i][j] == (k+1+48)){endP.x = i;endP.y = j;}
				visited[i][j] = 0;
			}
		totalStep += bfs(startP,endP);
	}
	printf("%d",totalStep);
}

C++: #include <iostream>
#include <string>
#include <algorithm>
#include <iomanip>
#include <vector>
#include <map>
#include <cmath>
#include <queue>
#include <utility>
#include <functional>
#include <deque>
#include <cctype>
#include <stack>
#include <bitset>
#include <set>

using ll = long long;
using namespace std;
typedef unsigned long long ull;
typedef pair<ll, ll>P;

const ll MOD = 1000000007;
const ll INF = 1 << 30;
const ll INF2 = 9000000000000000000LL;
const int dx[4] = { 1,0,-1,0 }, dy[4] = { 0,1,0,-1 };
const int tx[8] = { -1,0,1,-1,1,-1,0,1 }, ty[8] = { -1,-1,-1,0,0,1,1,1 };
#define ALL(x) (x).begin(),(x).end()

ll h, w, n, chx[10] = { 0 }, chy[10] = { 0 }, d[1010][1010] = { 0 };
char c[1010][1010];

int bfs(ll a, ll b, ll e, ll f) {
	queue<P> que;
	for (int i = 0;i < h;i++) {
		for (int j = 0;j < w;j++) {
			d[j][i] = INF;
		}
	}
	que.push(make_pair(a, b));
	d[a][b] = 0;
	while (que.size()) {
		P p = que.front();que.pop();
		if (p.first == e&&p.second == f) {
			break;
		}
		for (int i = 0;i < 4;i++) {
			ll nx = p.first + dx[i], ny = p.second + dy[i];
			if (0 <= nx&&nx < w && 0 <= ny&&ny < h&&c[nx][ny] != 'X'&&d[nx][ny] == INF) {
				que.push(make_pair(nx, ny));
				d[nx][ny] = d[p.first][p.second] + 1;
			}
		}
	}
	return d[e][f];
}


int main() {
	ll ans = 0;
	cin >> h >> w >> n;
	for (int i = 0;i < h;i++) {
		for (int j = 0;j < w;j++) {
			cin >> c[j][i];
			if (c[j][i] == 'S')chx[0] = j, chy[0] = i;
			else if (c[j][i] != 'S'&&c[j][i] != '.'&&c[j][i] != 'X') {
				chx[int(c[j][i] - '0')] = j, chy[(int)(c[j][i] - '0')] = i;
			}
		}
	}
	for (int i = 0;i < n;i++) {
		ans += bfs(chx[i], chy[i], chx[i + 1], chy[i + 1]);
	}
	cout << ans << endl;
}

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

using namespace std;

const int MAX_W = 1000;
const int MAX_H = 1000;
const int MAX_N = 9;

typedef pair<int, int> P;

int H,W,N;
char field[MAX_H][MAX_W];
int dist[MAX_H][MAX_W];

queue<P> que;

//using limits = std::numeric_limits<int>;

int limits = 99999;

void getStatus(int y, int x, int min_dist){
    for(int i = 0; i< H; i++) {
        for (int j = 0; j < W; j++) {
            if( i == y && j == x){
                cout << "$";
            }else {
                cout << field[i][j];
            }
        }
        cout << endl;
    }
    cout << "-------------min_dist:" << min_dist << endl;
}


int bfs(int goal){

    int gx,gy;

    while( que.size()){
        P p = que.front(); que.pop();
        int a = p.first;
        int b  = p.second;

        if( atoi(&field[p.first][p.second]) == goal ) { gy = p.first; gx = p.second; break; }

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

        for(int i=0; i< 4; i++){

            int ny = p.first + dy[i],
                nx = p.second+ dx[i];

            if( 0 <= nx
                && nx < W
                && 0<= ny
                && ny < H
                && field[ny][nx] != 'X'
                && dist[ny][nx] ==  limits ){

                que.push(P(ny,nx) );
                dist[ny][nx] = dist[p.first][p.second] + 1;

            }
        }
       // getStatus(p.first,p.second,dist[p.first][p.second]);
    }

    return dist[gy][gx];
}


void init_dist(){
    for(int i=0; i< H; i++){
        for(int j=0; j<W; j++){
            dist[i][j] = limits;
        }
    }
    queue<P>().swap(que);

}


void solve(){
    int sum = 0;
    for(int i = 0; i< H; i++){
        for(int j = 0; j< W; j++){

            if( field[i][j] == 'S'){
                init_dist();
                que.push(P(i,j));
                dist[i][j] = 0;
                sum += bfs(1);
            }

            for(int k = 1; k<N; k++){
                if( atoi(&field[i][j]) == k ) {
                    init_dist();
                    que.push(P(i,j));
                    dist[i][j] = 0;
                    sum+=bfs(k+1);
                }

            }
        }
    }

    cout << sum << endl;

}



int main() {

    while(1){

        string line;
        cin >> H >> W >> N;cin.ignore();
        if( H == 0 && W == 0 ){
            break;
        }


        for(int i = 0; i< H; i++){
            getline(cin,line);
            for(int j = 0; j< W; j++){
                field[i][j] = line[j];
            }
        }

        solve();

    }

    return 0;
}

/*
10 10 9
.X...X.S.X
6..5X..X1X
...XXXX..X
X..9X...X.
8.X2X..X3X
...XX.X4..
XX....7X..
X..X..XX..
X...X.XX..
..X.......
 */