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<queue>
#include<string.h>
#include<limits.h>
using namespace std;
const int MAXH = 1100;
const int INF = INT_MAX;
typedef pair<int, int> P;
int H,W,N;
char B[MAXH][MAXH];
int d[MAXH][MAXH];
int sx, sy;
int gx, gy;
int res;
int dx[5] = {1,0,-1,0};
int dy[5] = {0,1,0,-1};

void bfs()
{
	queue<P> que;
	que.push(P(sx,sy));
	d[sx][sy] = 0;
	
	while(que.size())
	{
		P p = que.front(); que.pop();
		
		if(p.first== gx && p.second == gy)break;
		for(int i = 0; i<4;i++)
		{
			int nx = p.first+ dx[i], ny = p.second + dy[i];

			if(B[nx][ny] != 'X' && d[nx][ny] ==INF)
				{
				que.push(P(nx,ny));
				d[nx][ny] = d[p.first][p.second] + 1;

				}
		}	
	}
	res+= d[gx][gy];
}

void rest()
{
	for(int i = 1; i<= W;i++)
		for(int j = 1; j<= H; j++)
			d[i][j] = INF;
}
void solve()
{
	for(int che = 1; che <= N; che++)
		for(int i = 1 ; i<= W;i++)
			for(int j = 1; j <= H; j++)
			{
				if(B[i][j] - '0' == che)
				{
					rest();
					gx = i; gy = j;
					bfs();
					sx = gx; sy = gy;
				}
			}	
	cout << res << endl;
}

int main()
{
	
	cin >>H>>W>>N;
	memset(B,'X',sizeof(B));
	for(int j = 1 ; j<= H;j++)
	{
		for(int i = 1; i <= W; i++)
		{
			cin >> B[i][j];
			if(B[i][j] == 'S')
				{sx = i; sy = j;}
		}	
		getchar();
	}

	res = 0;	
	solve();
	
}

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;
        }
    }
    while(que.size()){
        que.pop();
    }

}


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<bits/stdc++.h>
#define rep(i,n) for(ll i=0;i<n;++i)
#define rrep(i,n) for(int i=n-1;i>=0;--i)
#define yesno(flg) if(flg){cout<<"YES"<<endl;}else{cout<<"NO"<<endl;}
#define MAX_N 1002
#define i197 1000000007
#define Vi vector<int>
#define Vl vector<long long>
#define pb(a) push_back(a)

using namespace std;

typedef long long ll;
typedef pair<ll,ll> P1;
typedef pair<int,int> Pi;
typedef pair<double,Pi> Pdi;
typedef pair<ll,int>Pli;
typedef pair<P1,ll> P2;
const ll INF=10000000000000000001;
int dy[]={0, 0, 1, -1};
int dx[]={1, -1, 0, 0};
struct Road{double cost;int a,b;};
struct edge{int to,cost;};
struct pos{
	int x,y,cost;
};
char c[1001][1001]={};
int a[1001][1001]={};
int dp[1001][1001]={};

int main() {

	int w,h,n;
	cin>>h>>w>>n;

	int si=0,sj=0;
	rep(i,h){
		rep(j,w){
			cin>>c[j][i];
			if(c[j][i]=='S'){
				sj=j;
				si=i;
				a[j][i]=-1;
			}else if(c[j][i]!='.'&&c[j][i]!='X'){
				a[j][i]=c[j][i]-48;
			}

		}
	}
	queue<pos> que;
	ll total=0;
	for(int i=1; i<n+1; i++){
		pos pos1={sj,si,0};
		que.push(pos1);
		while(!que.empty()){
			pos pos2=que.front();que.pop();
			if(dp[pos2.x][pos2.y]==1)continue;
			if(a[pos2.x][pos2.y]==0&&c[pos2.x][pos2.y]!='.')continue;
			if(a[pos2.x][pos2.y]==i){
				total+=pos2.cost;
				while(!que.empty())que.pop();
				si=pos2.y;
				sj=pos2.x;
				break;
			}
			dp[pos2.x][pos2.y]=1;
			pos pos3={pos2.x+1,pos2.y,pos2.cost+1};
			que.push(pos3);
			pos pos4={pos2.x-1,pos2.y,pos2.cost+1};
			que.push(pos4);
			pos pos5={pos2.x,pos2.y+1,pos2.cost+1};
			que.push(pos5);
			pos pos6={pos2.x,pos2.y-1,pos2.cost+1};
			que.push(pos6);
		}
		rep(j,h)rep(k,w)dp[k][j]=0;
	}
	cout<<total<<endl;

	return 0;
}