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>
using namespace std;
int n,m,k,f[4][2]={0,1,0,-1,1,0,-1,0},maxx=-9999;
char map[1010][1010];
int head=1,tail=1,sx,sy;
int dp[1010][1010];
struct node{
	int x,y,sum,ans;
}a[1000010];
int main()
{
	cin>>n>>m>>k;
	for(int i=1;i<=n;i++)
		for(int j=1;j<=m;j++)
		{
			cin>>map[i][j];
			if(map[i][j]=='S') 
			{
				sx=i;
				sy=j;
			}
		}
	a[head].x=sx;
	a[head].y=sy;
	a[head].sum=1;
	a[head].ans=1;
	dp[sx][sy]=1;
	tail++;
	while(head<tail) 
	{
		int flag=0;
		int nx=a[head].x,ny=a[head].y;
		if(a[head].ans==head)
		{
			maxx=a[head].sum;
		}
		for(int i=0;i<=3;i++)
		{
			int tx=nx+f[i][0];
			int ty=ny+f[i][1];
			if(tx<1||tx>n||ty<1||ty>m||map[tx][ty]=='X') continue;
			if(map[tx][ty]>='1'&&map[tx][ty]<='9') 
			{
				if(a[head].ans<map[tx][ty]-48)
				flag=1;
			}
			if(flag) continue;
			if(map[tx][ty]>='1'&&map[tx][ty]<='9')
			{
				if(a[head].sum+1<dp[tx][ty]||dp[tx][ty]==0)
				{
					a[tail].x=tx;
					a[tail].y=ty;
					a[tail].ans=a[head].ans+1;
					a[tail].sum=a[head].sum+1;
					dp[tx][ty]=a[tail].sum;
					tail++;
				}
			}
			else if(a[head].sum+1<dp[tx][ty]||dp[tx][ty]==0)
			{
				a[tail].x=tx;
				a[tail].y=ty;
				a[tail].sum=a[head].sum+1;
				dp[tx][ty]=a[tail].sum;
				tail++;
			}
		}
		head++; 
	}
	cout<<head-1;
	return 0;
/*
4 5 2
. X . . 1
. . . . X
. X X . S
. 2 . X .
*/
}

C++: #include<iostream>
#include<queue>
#include<string>
#include<utility>
#include<array>

#define h first
#define w second 

using namespace std;

string map[1002];
int cost[1002][1002] {};


int main()
{
    int H{ 0 };
    int W{ 0 };
    int N{ 0 };

    int nowH{ 0 };
    int nowW{ 0 };

    queue< pair<int, int> > path; //????????? (h, w)

    cin >> H >> W >> N;

    for(int i = 0; i < H; i++)
    {
        //??\???
        cin >> map[i];
        for(int j = 0; j < W; j++)
        {
            //??????????????°????????¢?´¢
            if(map[i][j] == 'S')
            {
                nowH = i;
                nowW = j;
            }
        }
    }

    //???????????§??\???



    //?????????????§£???
    path.push(make_pair(nowH, nowW));

    int nowHP{ 1 };
    while(nowHP <= N)
    {
        pair<int, int> now = path.front();
        path.pop();

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

        for(int i = 0; i < 4; i++)
        {
            int nextH = now.h + dy[i];
            int nextW = now.w + dx[i];

            if(0 <= nextH && nextH < H && 0 <= nextW && nextW < W)
            {
                //?§????????????§???????????\??????????????£??????
                if(map[nextH][nextW] != 'X' && cost[nextH][nextW] == 0)
                {
                    cost[nextH][nextW] = cost[now.h][now.w] + 1;
                    path.push(make_pair(nextH, nextW));
                }
                //????????????????????\??´??????
                if(map[nextH][nextW] == char(nowHP + 48))
                {
                    if(nowHP == N)
                    {
                        cout << cost[nextH][nextW] << endl;
                        return 0;
                    }
                    else
                    {
                        nowHP++;
                        while(!path.empty())path.pop();
                        path.push(make_pair(nextH, nextW));

                        int tmp = cost[nextH][nextW];

                        for(int x = 0; x < W; x++)
                            for(int y = 0; y < H; y++)
                                cost[y][x] = 0;

                        cost[nextH][nextW] = tmp;
                        i = 10;
                    }
                    
                }
//                cout << map[nextH][nextW] << " / h : " << nextH << " w : " << nextW << " :: " << cost[nextH][nextW] << endl;
            }
        }

    }



    return 0;
}

C++: #include <iostream>
#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>;

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.......
 */