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

#define MaxW 1000
#define MaxH 1000
#define MaxN 1000
#define INF 99999
int H,W,N;
int d[MaxN + 1][MaxN + 1];
char pos[MaxH][MaxW];
int dx[4] = {-1,0,1,0},dy[4] = {0,1,0,-1};
bool visited[MaxH][MaxW];

typedef struct Node{
    int x,y;
}Node;

bool judge(int x, int y){
    if (x >= 0 && x < H && y>= 0 && y< W){
        return true;
    }
    return false;
}

int bfs(int s, int e){
    queue<Node> Q;
    int sx,sy,ex,ey;//record the position of start and end point
    for (int i = 0; i < H; ++i) {
        for (int j = 0; j < W; ++j) {
            visited[i][j] = false;
            d[i][j] = 0;
            if (pos[i][j] - '0' == s){
                sx = i;sy = j;
            } else if(pos[i][j] - '0' == e){
                ex = i;ey = j;
            }
        }
    }
    Node S;
    S.x = sx;
    S.y = sy;
    Q.push(S);
    visited[sx][sy] = true;
    bool find = false;

    while(!Q.empty()){
        Node T = Q.front();
        Q.pop();
        for (int i = 0; i < 4; ++i) {
            int nx = T.x + dx[i];
            int ny = T.y + dy[i];
            if (!visited[nx][ny] && judge(nx, ny) && pos[nx][ny] != 'X') {
                Node p;
                p.x = nx;
                p.y = ny;
                Q.push(p);
                visited[nx][ny] = true;
                d[nx][ny] = d[T.x][T.y] + 1;
            }
            if (nx == ex && ny == ey){
                find = true;
                break;
            }
        }
        if(find == true)
            break;
    }
    return d[ex][ey];
}

int main(){
    while(cin>>H>>W>>N){
        if (H == 0 && W == 0 )
            break;
        for (int i = 0; i < H; ++i) {
            for (int j = 0; j < W; ++j) {
                cin>>pos[i][j];
                if (pos[i][j] == 'S')
                    pos[i][j] = '0';
            }
        }
        for (int k = 0; k < H; ++k) {
            for (int i = 0; i < W ; ++i) {
                d[k][i] = 0;
            }
        }int t = 0;
        for (int l = 0; l < N; ++l) {
            t += bfs(l,l+1);
        }

        cout<<t<<endl;
    }

    return 0;
}

C++: #include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <map>
#include <queue>
#include <cstdlib>
#include <algorithm>
#include <iterator>
using namespace std;

int H,W,N;
int dx[4]={1,0,-1,0},dy[4]={0,1,0,-1};
char MAP[1000+1][1000+1];
int f[1000+1][1000+1];
int d[1000+1][1000+1];
int main(){
	cin >> H >> W >> N;
	queue<char> qux;
	queue<char> quy;
	vector<int> ans(N+1);
	for(int i=1; i<H+1; ++i){
		for(int j=1; j<W+1; ++j){
			cin >> MAP[i][j];
			f[i][j]=0;
			if(MAP[i][j]=='S'){
				qux.push(i);
				quy.push(j);
				f[i][j]=1;
				d[i][j]=0;
			}
		}
	}
	int x;
	int y;
	for(int i=1; i<N+1; ++i){
		while(qux.size()&&quy.size()){
			x=qux.front();
			y=quy.front();
			cout << x << " " << y << " " << d[x][y] << "\n";
			qux.pop();
			quy.pop();
			//if('0'<=MAP[x][y]&&MAP[x][y]<='9'){
				//if(((int)MAP[x][y]-'0')==i) {
			if(atoi(&MAP[x][y])==i){
					ans[i]=d[x][y];
					for(int j=1; j<H+1; ++j){
						for(int k=1; k<W+1; ++k){
							f[i][j]=0;
						}
					}
					d[x][y]=0;
					break;
				}
			//}
			for(int j=0; j<4; ++j){
				int nx=x+dx[j];
				int ny=y+dy[j];
				if(1<=nx&&nx<=H&&1<=ny&&ny<=W&&MAP[nx][ny]!='X'&&f[nx][ny]==0){
					qux.push(nx);
					quy.push(ny);
					f[nx][ny]=1;
					d[nx][ny]=d[x][y]+1;
				}
			}
		}
	}
	int ANS=0;
	for(int i=1; i<N+1; ++i){
		ANS+=ans[i];
	}
	cout << ANS << "\n";
	return 0;
}

C++: import java.util.*;
import java.math.*;
import java.io.*;
import java.util.regex.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.lang.System.*;

public class Main {
	Scanner cin;
	class State{
		int time,x,y;
		State(int time,int x,int y){
			this.time=time;
			this.x=x;
			this.y=y;
		}
	}
	void run(){
		cin=new Scanner(System.in);
		int H=cin.nextInt(),W=cin.nextInt(),N=cin.nextInt();
		String[] MAP=new String[H];
		int []dx={1,0,-1,0},dy={0,1,0,-1};
		int result=0;
		for(int i=0;i<H;i++)MAP[i]=cin.next().replaceAll("S","0");
		for(int i=0;i<N;i++){
			int sx=-1,sy=-1;
			Queue<State> que=new LinkedList<State>();
			Boolean[][] visited=new Boolean[H][W];
			for(int p=0;p<H;p++){
				for(int q=0;q<W;q++){
					visited[p][q]=false;
					if(MAP[p].charAt(q)==i+'0'){
						sx=q;sy=p;
					}	
				}	
			}	
			que.add(new State(0,sx,sy));
			while(!que.isEmpty()){
				State now=que.poll();
				if(MAP[now.y].charAt(now.x)==i+1+'0'){
					result+=now.time;
					break;
				}
				for(int k=0;k<4;k++){
					int nx=now.x+dx[k],ny=now.y+dy[k];
					if(nx>=0&&nx<W&&ny>=0&&ny<H){
						if(visited[ny][nx]==false&&MAP[ny].charAt(nx)!='X'){
							visited[ny][nx]=true;
							que.add(new State(now.time+1,nx,ny));
						}
					}
				}
			}
		}
		printf("%d\n",result);
	}

	void printf(String format,Object... args){
		System.out.printf(format, args);
	}

	public static void main(String[] args) {
		new Main().run();
	}

}