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 <algorithm>
#include <vector>
#include <queue>
using namespace std;
int H, W, N;

char world[1002][1002];

pair<int, int> S;


vector<pair<int, int> > getNeighbors(pair<int, int> xs){
    vector<pair<int, int> > v;
    int dx[4] = {1, 0, -1, 0};
    int dy[4] = {0, 1, 0, -1};
    for(int i = 0; i < 4; i++){
        int nx = dx[i] + xs.first;
        int ny = dy[i] + xs.second;
        if (world[nx][ny] != 'X') {
            v.push_back(pair<int, int>(nx, ny));
        }
    }
    return v;
}

bool isAbnormal(vector<vector<bool> >& trails, const pair<int, int>& xs){
    if (trails[xs.first][xs.second]){
        return false;
    }else{
        trails[xs.first][xs.second] = true;
        return true;
    }
}

// pair<int, pair<int, int> > solve(char goal, const vector<pair<int, int> >& v, int depth){
//     vector<pair<int, int> > v2;
//     vector<vector<bool> > trails = vector<vector<bool> >(H + 2, vector<bool>(W + 2, false));

//     for(auto target: v){
//         vector<pair<int, int> > neighbors = getNeighbors(target);
//         for(auto x: neighbors){
//             if (world[x.first][x.second] == goal) {
//                 return pair<int, pair<int, int> >(depth + 1, x);
//             }
//             if (isAbnormal(trails, x)){
//                 v2.push_back(x);
//             }
//         }
//     }
//     return solve(goal, v2, depth + 1);
// }

pair<int, pair<int, int> > solve(char goal, pair<int, int> s){
    vector<pair<int, int> >  v2;
    vector<vector<bool> > trails = vector<vector<bool> >(H + 2, vector<bool>(W + 2, false));

    queue<pair<int, pair<int, int> > > q;
    q.push(pair<int, pair<int, int> >(0, s));

    pair<int, pair<int, int> > target;
    while(true){
        target = q.front();
        q.pop();
        
        int depth = target.first;
        pair<int, int> xy = target.second;
        
        vector<pair<int, int> > neighbors = getNeighbors(xy);
        for(auto neighbor: neighbors){
            int x = neighbor.first;
            int y = neighbor.second;
            if (world[x][y] == goal) {
                return pair<int, pair<int, int> >(depth + 1, neighbor);
            }
            if (isAbnormal(trails, neighbor)){
                q.push(pair<int, pair<int, int> >(depth + 1, neighbor));
            }
        }
    }
}

    


void input(){
    cin >> H >> W >> N;
    for(int i = 1; i < H + 1; i++){
        for (int j = 1; j < W + 1; j++) {
            cin >> world[i][j];
            if (world[i][j] == 'S') {
                S = pair<int, int>(i, j);
            }
        }
    }
}

void init(){
    for (int j = 0; j < W + 2; j++) {
        world[0][j] = 'X';
        world[H + 1][j] = 'X';
    }
    for (int i = 0; i < H + 2; i++) {
        world[i][0] = 'X';
        world[i][W + 1] = 'X';
    }
}

int main (int argc, char* argv[]){
    input();

    init();
    
    int sum = 0;
    for (char g = '1'; g < '1' + N; g++){
        pair<int, pair<int, int> > res = solve(g, S);
        sum += res.first;
        S = res.second;
    }

    cout << sum << endl;

    return 0;
}

C++: #include<iostream>
#include<queue>
#include<algorithm>
#define INFTY 1000000
#define MAX 1000

typedef std::pair<int,int> P;

int d[MAX][MAX],h,w,N,PX[4]={1,-1,0,0},PY[4]={0,0,1,-1},sum=0;
char ch[MAX][MAX];

int bfs(P p,P q){
	for(int i=0;i<h;++i){
		for(int j=0;j<w;++j){
			d[i][j]=INFTY;
		}
	}
	std::queue<P> Q;
	Q.push(p);
	while(!Q.empty()){
		P u=Q.front();Q.pop();
		for(int i=0;i<4;++i){
			if(u.first+PX[i]>=0&&u.first+PX[i]<h&&u.second+PY[i]<w&&u.second+PY[i]>=0&&ch[u.first+PX[i]][u.second+PY[i]]!='X'){
				if(P(u.first+PX[i],u.second+PY[i])==q)
					return d[q.first-p.first][q.second-p.second];
				else{
					std::min(d[u.first+PX[i]-p.first][u.second+PY[i]-p.second],d[u.first-p.first][u.second-p.second]+1);
					Q.push(P(u.first+PX[i],u.second+PY[i]));
				}
			}
		}
	}
}

void solve(){
	int n=1;
	P s,p[10];
	for(int i=0;i<h;++i){
		for(int j=0;j<w;++j){
			if(ch[i][j]=='S')
				s.first=i;s.second=j;
			if(ch[i][j]==char(n)){
				p[n]=P(i,j);
				++n;
			}
		}
	}

	sum+=bfs(s,p[1]);
	for(int i=1;i<9;++i){
		sum+=bfs(p[i],p[i+1]);
	}
}

int main(){
	std::cin>>h>>w>>N;
	for(int i=0;i<h;++i){
		for(int j=0;j<w;++j){
			std::cin>>ch[i][j];
		}
	}
	solve();
	std::cout<<sum<<std::endl;
	return 0;
}

C++: #include <iostream>
#include <queue>

using namespace std;

const int INFTY=1<<29;

int calc(vector<string>& grid,int i,int j,char d)
{
	int h=grid.size(),w=grid[0].size();
	vector<vector<int> > cost(h,vector<int>(w,INFTY));
	queue<pair<int,int> > q;
	cost[i][j]=0;
	q.push(make_pair(i,j));
	while(q.size()){
		int ci=q.front().first,cj=q.front().second; q.pop();
		if(grid[ci][cj]==d)
			return cost[ci][cj];
		int di[]={-1,1,0,0},dj[]={0,0,-1,1};
		for(int k=0;k<4;k++){
			int ni=ci+di[k],nj=cj+dj[k];
			if(ni<0 || h<=ni || nj<0 || w<=nj)
				continue;
			if(grid[ni][nj]=='X' || cost[ni][nj]<=cost[ci][cj]+1)
				continue;
			cost[ni][nj]=cost[ci][cj]+1;
			q.push(make_pair(ni,nj));
		}
	}
	return INFTY;
}

int main()
{
	for(int h,w,n;cin>>h>>w>>n && h|w|n;){
		vector<string> grid(h);
		for(int i=0;i<h;i++)
			cin>>grid[i];
		int res=0;
		for(int k=0;k<n;k++){
			char s=k?'0'+k:'S';
			char d='1'+k;
			for(int i=0;i<h;i++)
				for(int j=0;j<w;j++)
					if(grid[i][j]==s)
						res+=calc(grid,i,j,d);
		}
		cout<<res<<endl;
	}
	
	return 0;
}