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 <cstdio>
#include <limits>
#include <queue>

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


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::infinity() ){

                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::infinity();
        }
    }
    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.......
 */

C++: #include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <queue>

using namespace std;

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

int dist[1010][1010];

int main(void){
	int h, w, n; cin >> h >> w >> n;
	vector<string> fieldMap(h);
	queue<pair<int, int> > que;
	for(int i=0; i<h; i++){
		cin >>  fieldMap[i];
		for(int j=0; j<w; j++){
			if(fieldMap[i][j] == 'S'){
				fieldMap[i][j] = '0';
				que.push(make_pair(i, j));
			}
		}
	}

	int ans = 0;
	fill(dist[0], dist[h], -1);
	for(int g=1; g<=n; g++){
		pair<int, int> pos = que.front();
		dist[pos.first][pos.second] = 0;
		bool find = false;
		while(!que.empty() && !find){
			pair<int, int> pos = que.front(); que.pop();
			int ncost = dist[pos.first][pos.second];
			for(int i=0; i<4; i++){
				int ny = pos.first + dy[i];
				int nx = pos.second + dx[i];
				if(ny < 0 || h <= ny || nx < 0 || w <= nx) continue;
				if(fieldMap[ny][nx] == 'X') continue;
				if(fieldMap[ny][nx] - '0' == g){
					ans += ncost + 1;
					while(!que.empty()) que.pop();
					que.push(make_pair(ny, nx));
					fill(dist[0], dist[h], -1);
					dist[ny][nx] = 0;
					find = true;
					break;
				}
				if(dist[ny][nx] == -1){
					dist[ny][nx] = ncost + 1;
					que.push(make_pair(ny, nx));
				}
			}
		}
	}
	cout << ans << endl;
	return 0;
}

C++: #include <algorithm>
#include <cmath>
#include <climits>
#include <deque>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <map> //pair is also included in this library
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <unordered_map>
#include <vector>

#define REP(i, s, n) for(int i = (int)(s); i < (int)(n); i++)
#define fst first
#define snd second
#define MP make_pair //incase c++11 or later is not available

using namespace std;

typedef long long int ll;
typedef vector<int> VI;
typedef vector<ll> VL;
typedef pair<int, int> PII;
typedef pair<ll, ll> PLL;

//prefer define statement
//for reason that const int ver. of INF will raise a silly warning (unused variable)
#define INF (INT_MAX/3)
#define LIM_INF (INT_MAX)
//const int INF = INT_MAX/3;

/*------------------------------------------------------------------------------*/

int cost[1100][1100];

int main(){
  int H, W, N;
  cin >> H >> W >> N;
  vector<string> s;

  s.push_back(string(W+2, 'X'));
  REP(i, 0, H){
    string tmp;
    cin >> tmp;
    s.push_back('X' + tmp + 'X');
  }
  s.push_back(string(W+2, 'X'));

  vector<PII> v(N+1);
  REP(i, 0, H+2){
    REP(j, 0, W+2){
      char c = s[i][j];
      if(c >= '1' && c <= '9'){
        v[c-'0'] = {i, j};
      } else if(c == 'S'){
        v[0] = {i, j};
      }
    }
    //cout << s[i] << endl;
  }

  int dest = 0, res = 0;
  REP(i, 0, N){
    queue<PII> q;
    q.push(v[dest]);
    memset(cost, -1, sizeof(cost));
    cost[v[dest].fst][v[dest].snd] = 0;
    while(!q.empty()){
      PII a = q.front(); q.pop();
      const int dx[4] = {-1, 0, 1, 0};
      const int dy[4] = {0, -1, 0, 1};
      if(s[a.fst][a.snd] == i + '1'){
        res += cost[a.fst][a.snd];
        dest++;
        break;
      }
      REP(i, 0, 4){
        int ny = a.fst + dy[i];
        int nx = a.snd + dx[i];
        if(s[ny][nx] != 'X' && !(cost[ny][nx] + 1)){//cost[ny][nx] + 1 == 0 if not searched
          cost[ny][nx] = cost[a.fst][a.snd] + 1;
          q.push({ny, nx});
        }
      }
    }
  }
  cout << res << endl;

  return 0;
}