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 <memory>
#include <cstring>
#include <string>
#include <memory.h>
using namespace std;
int m,n,t;
int cnt;
char c;
char map[1010][1010];
bool vis[1010][1010];
struct node
{
	int x,y;
	int step;
}start;
int way[4][2] = {{-1,0},{0,1},{1,0},{0,-1}};
void bfs()
{
	queue <node> abc;
	abc.push(start);
	while(!abc.empty())
	{
		node k = abc.front(); 
		abc.pop();
		if(map[k.y][k.x] == c)
		{
			cnt+=k.step;
			k.step = 0;
			memset(vis,0,sizeof(vis));
			while(!abc.empty())
			abc.pop();
			c++;
			t--;
		}
		if(t==0)
		{
			return;
		}
		for(int i = 0;i<4;i++)
		{
			int dx = k.x+way[i][0];
			int dy = k.y+way[i][1];
			if(dx>=0 && dx<n && dy>=0 && dy<m && !vis[dy][dx] &&map[dy][dx]!='X')
			{
				node temp;
				temp.x = dx;
				temp.y = dy;
				temp.step = k.step+1;
				abc.push(temp);
				vis[dy][dx]=1;
			}
		}
	}	
} 
int main()
{
	while(cin >> m >> n >> t)
	{
		cnt = 0;
		c = '1';
		memset(vis,0,sizeof(vis));
		memset(map,0,sizeof(map));
		for(int i = 0;i<m;i++)
		{
			for(int j = 0;j<n;j++)
			{
				cin >> map[i][j];
				if(map[i][j] == 'S')
				{
					start.x = j;
					start.y = i;
					start.step = 0;
				}
			}
		}
		bfs();
		cout << cnt << endl;
	}
	return 0;
}

C++: //???2:???????????¢?´¢
#include <stdio.h>
#include <stack>
#include <math.h>
#include <queue>

using namespace std;

int height,width,N;
char** table;

struct Info{
	int cheese_id,row,col;
};

struct Data{
	int row,col,dist;
	char pre_move;
};

bool rangeCheck(int row,int col){
	if(row >= 0 && row <= height-1 && col >=0 && col <= width-1)return true;
	else{
		return false;
	}
}

int func(int row,int col,int goal_row,int goal_col,int dist){
	queue<Data> Q;
	Data data,tmp;
	data.row = row;
	data.col = col;
	data.dist = 0;
	data.pre_move = 'F';
	Q.push(data);


	int ret = 0;

	while(!Q.empty()){
		tmp = Q.front();
		Q.pop();

		if(tmp.col == goal_col && tmp.row == goal_row){
			ret = tmp.dist;
			break;
		}

		if(rangeCheck(tmp.row-1,tmp.col) == true && tmp.pre_move != 'D' && table[tmp.row-1][tmp.col] != 'X'){
			Data new_data;
			new_data.row = tmp.row-1;
			new_data.col = tmp.col;
			new_data.dist = tmp.dist+1;
			new_data.pre_move = 'U';
			Q.push(new_data);
		}
		if(rangeCheck(tmp.row+1,tmp.col) == true && tmp.pre_move != 'U' && table[tmp.row+1][tmp.col] != 'X'){
			Data new_data;
			new_data.row = tmp.row+1;
			new_data.col = tmp.col;
			new_data.dist = tmp.dist+1;
			new_data.pre_move = 'D';
			Q.push(new_data);
		}
		if(rangeCheck(tmp.row,tmp.col-1) == true && tmp.pre_move != 'R' && table[tmp.row][tmp.col-1] != 'X'){
			Data new_data;
			new_data.row = tmp.row;
			new_data.col = tmp.col-1;
			new_data.dist = tmp.dist+1;
			new_data.pre_move = 'L';
			Q.push(new_data);
		}
		if(rangeCheck(tmp.row,tmp.col+1) == true && tmp.pre_move != 'L' && table[tmp.row][tmp.col+1] != 'X'){
			Data new_data;
			new_data.row = tmp.row;
			new_data.col = tmp.col+1;
			new_data.dist = tmp.dist+1;
			new_data.pre_move = 'R';
			Q.push(new_data);
		}
	}

	return ret;
}

int main(){

	scanf("%d %d %d",&height,&width,&N);
	table = new char*[1000];
	Info info[N+1];
	int info_index = 0,total_dist = 0;


	for(int i=0; i < height; i++){
		table[i] = new char[1001];

		scanf("%s",table[i]);

		for(int k = 0; k <width; k++){

			if(table[i][k] == 'S'){
				info[info_index].cheese_id = 0;
				info[info_index].row = i;
				info[info_index].col = k;
				info_index++;
			}else if(table[i][k] >= '1' && table[i][k] <= '9'){
				info[info_index].cheese_id = table[i][k] - '0';
				info[info_index].row = i;
				info[info_index].col = k;
				info_index++;
			}
		}
	}

	for(int i=1; i <= N; i++){
		for(int k=N; k >= i; k--){
			if(info[k].cheese_id < info[k-1].cheese_id)swap(info[k],info[k-1]);
		}
	}

	for(int i = 0; i <= N-1; i++){
		total_dist += func(info[i].row,info[i].col,info[i+1].row,info[i+1].col,0);
	}

	printf("%d\n",total_dist);

    return 0;
}

C++: #include <iostream>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <math.h>
#include <string>
#include <string.h>
#include <stack>
#include <queue>
#include <vector>
#include <utility>
#include <set>
#include <map>
#include <stdlib.h>

using namespace std;

#define ll long long
#define ld long double
#define EPS 0.0000000001
#define INF 10000000000LL
#define rep(i,n) for(i=0;i<n;i++)

typedef pair<int,int> pii;

char a[105][105];
int used[105][105]={};
int h,w;
pii place[1000];

int search(int sx,int sy,int gx,int gy){
    int i,j;
    int dx[4]={-1,0,1,0};
    int dy[4]={0,-1,0,1};
    rep(i,h)rep(j,w)used[i][j]=0;
    int ans=0;
    used[sx][sy]++;
    queue<pii> q1,q2;
    q1.push(pii(sx,sy));
    while(1){
        bool f=false;
        while(q1.size()){
            int x=q1.front().first;
            int y=q1.front().second;
            if(x==gx && y==gy){
                f=true;
                break;
            }
            rep(i,4){
                int nx=x+dx[i];//next
                int ny=y+dy[i];//next
                if(nx<0 || nx>=h || ny<0 || ny>=w)continue;
                if(a[nx][ny]!='X' && used[nx][ny]==0){
                    used[nx][ny]++;
                    q2.push(pii(nx,ny));
                }
            }
            q1.pop();
        }

        if(f)break;

        while(q2.size()){
            q1.push(pii(q2.front().first,q2.front().second));
            q2.pop();
        }
        ans++;
    }
    return ans;
}

int main(void) {
    int n,i,j;
    cin>>h>>w>>n;
    rep(i,h){
        cin>>a[i];
        rep(j,w)
            if(a[i][j]=='S'){
                place[0].first=i;
                place[0].second=j;
            }else if(a[i][j]>'0' && a[i][j]<='n'){
                place[a[i][j]-'0'].first=i;
                place[a[i][j]-'0'].second=j;
            }
    }
    
    int ans=0;
    rep(i,n)
        ans+=search(place[i].first,place[i].second,place[i+1].first,place[i+1].second);
        
    cout<<ans<<endl;
    return 0;
}