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<utility>
using namespace std;
#define INF 9999
typedef pair<int,int> P;
int w;//???
int h;//???
int num;//??\????????° 
P pos;//???????????? 
char fty[1005][1005]; 
P f_pos[10];
int step;
int mp[1005][1005];
void bfs(int x,int y){
	for(int i=0;i<h;i++){
		for(int j=0;j<w;j++){
			mp[i][j]=INF;
		}
	}
	mp[pos.first][pos.second]=0;
	
	int dx[4]={1,0,-1,0};
	int dy[4]={0,1,0,-1};
	queue<P> que;
	que.push(pos);
	while(que.size()){
		P s = que.front();
		que.pop();
		if(s.first==x&&s.second==y) break;
		for(int i=0;i<4;i++){
			for(int j=0;j<4;j++){
				int nx = s.first+dx[i];
				int ny = s.second+dy[i];
				if(nx>=0&&nx<h&&ny>=0&&ny<w&&mp[nx][ny]==INF&&fty[nx][ny]!='X'){
					mp[nx][ny]=mp[s.first][s.second]+1;
					que.push(P(nx,ny));
				}
			}
		}
	}
	step+=mp[x][y]; 
	pos.first=x;
	pos.second=y;
}
int main(){
	cin>>h>>w>>num;
	step=0;
	for(int i=0;i<h;i++){
		for(int j=0;j<w;j++){
			cin>>fty[i][j];
			for(int k=1;k<=num;k++){
				if(fty[i][j]-48==k){
					f_pos[k].first=i;
					f_pos[k].second=j;
					break;
				}
				
			}
			if(fty[i][j]=='S'){
				pos.first=i;
				pos.second=j;
			}
		}
	}
	step=0;
	for(int k=1;k<=num;k++){
		bfs(f_pos[k].first,f_pos[k].second);
	}
	cout<<step;
}

C++: #include<cstdio>
#include<iostream>
#include<string>
#include<queue>
#include <algorithm>
#include<map>
#define MAX 1001
using namespace std;

char xy[MAX][MAX];
int cost[MAX][MAX];
int hp[MAX][MAX];

const int INF=1>>21;

struct state{
  int x;
  int y;
  int co;
  int hp;
  state(){}
  state(int x,int y,int co,int hp):
    x(x),y(y),co(co),hp(hp){}
};

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

int H,W,N;

int solve(int x,int y){
  int i,j;
  queue<state> q;
  q.push( state(x,y,0,1) );
  cost[x][y]=0;

  while( !(q.empty()) ){

    state p = q.front();
    q.pop();

    x=p.x;
    y=p.y;

    int hpf=0;


    for(i=0;i<4;i++){

      if( x+dx[i] < 0 || x+dx[i] >= W || y+dy[i] < 0 || y+dy[i] >= H )
	continue;

      if(xy[y+dy[i]][x+dx[i]]=='X') continue;

      if(cost[x+dx[i]][y+dy[i]]<p.co){
	if(hp[x+dx[i]][y+dy[i]]==p.hp){
	  continue;
	}
      }
      
      if(xy[y+dy[i]][x+dx[i]]-'0' == p.hp){
	hpf=1;
	
	if(p.hp >= N){
	  return p.co+1;
	}
	
	while( !(q.empty()) ){
	  q.pop();
	}
	
	q.push( state(x+dx[i],y+dy[i],p.co+1,p.hp+hpf) );
	
	break;
	
      }
      
      cost[x][y]=p.co;
      hp[x][y]=p.hp;

      q.push( state(x+dx[i],y+dy[i],p.co+1,p.hp) );


    }

  }

  return -1;
}

main(){
  int i,j,sx,sy;

  cin >> H >> W >> N;

  for(i=0;i<H;i++){
    scanf("%s",xy[i]);
    for(j=0;j<W;j++){
      if(xy[i][j]=='S'){
	sx=j;
	sy=i;
      }
    }
  }

  int n=solve(sx,sy);

  cout << n << endl; 
  
  return 0;
}

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

using namespace std;

const int INF = 100000000;
const int MAX_X = 1000, MAX_Y = 1000, MAX_N = 9;
typedef pair<int, int> P;

int X, Y, N;
char grid[MAX_X+5][MAX_Y+5];
int dp[MAX_X+5][MAX_Y+5];
P chease_pos[MAX_X+5];
int dx[4] = {1, 0, -1,  0};
int dy[4] = {0, 1,  0, -1};

int bfs(P start_pos, P end_pos) {
    // search the min path from start_pos to end_pos
    queue<P> que;

    // initialize
    for(int i = 0; i < X; i++) {
        for(int j = 0; j < Y; j++) {
            dp[i][j] = INF;
        }
    }

    // first push
    que.push(start_pos);
    dp[start_pos.first][start_pos.second] = 0;

    while(que.size()) {
        // pop
        P p = que.front(); que.pop();

        // stop condition
        if(p.first == end_pos.first &&
           p.second == end_pos.second) {
            break;
        }

        // search
        for(int i = 0; i < 4; i++) {
            int nx = p.first+dx[i];
            int ny = p.second+dy[i];

            // grid check
            if(nx >= 0 && nx < X && ny >= 0 && ny < Y) {
                // check  X or not
                if(grid[nx][ny] != 'X') {
                    // whether first visit or not
                    if(dp[nx][ny] == INF) {
                        dp[nx][ny] = dp[p.first][p.second] + 1;
                        que.push(P(nx, ny));
                    }
                }
            }
        }

    }

    return dp[end_pos.first][end_pos.second];
}

int solve() {
    // input
    cin >> X >> Y >> N;
    for(int i = 0; i < X; i++) {
        cin >> grid[i];
    }

    P start_pos, end_pos;
    // search where chease exists and start_pos
    for(int i = 0; i < X; i++) {
        for(int j = 0; j < Y; j++) {
            if(grid[i][j] == 'S') {
                start_pos = P(i, j);
            } else if(grid[i][j] != 'X' && grid[i][j] != '.') {
                int num = (int)grid[i][j] - (int)'0';
                chease_pos[num] = P(i, j);
            }
        }
    }

    int count = 0;
    for(int i = 0; i < N; i++) {
        // set pos
        if(i != 0) {
            start_pos = end_pos;
        }
        end_pos = chease_pos[i+1];

        // bfs
        count += bfs(start_pos, end_pos);
    }

    cout << count << endl;
    return 0;
}


int main() {
    solve();
    return 0;
}

C++: #include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <string>
#include <functional>
#include <array>
#include <stack>
#include <queue>
#include <chrono>
#include <numeric>

#pragma warning(disable:4996)
#define REP(i,n) for(int i = 0 ; i < n ; ++i)
typedef long long Int;

using namespace std;

struct point{
	int j, i,step;
	point(int i_, int j_,int s) :i(i_), j(j_),step(s){}
};

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

queue<point> que;
char tile[1000][1000];
int H, W;
bool ed[1000][1000];

point solve(char target)
{
	while (!que.empty()){
		point now(que.front());
		ed[now.j][now.i] = true;
		que.pop();
		REP(i, 4){
			int x = now.j + dx[i];
			int y = now.i + dy[i];

			if (x < 0 || y < 0 || x > W || y > H || ed[x][y])
				continue;

			if (tile[y][x] == target){
				return point(y, x,now.step+1);
			}

			if (tile[y][x] != 'X'){
				que.emplace(y, x, now.step + 1);
				ed[x][y] = true;
			}
		}
	}
}

int main()
{
	cin.tie(0); ios::sync_with_stdio(false);
	fstream fs("input.txt");
	////////////ここから開始///////////
	int n(0);
	cin >> H >> W >> n;

	REP(i, 1000)REP(j, 1000)tile[i][j] = 'X';

	REP(i, H)REP(j, W)fs >> tile[i][j];

	REP(i, H)REP(j, W){ if (tile[i][j] == 'S')que.emplace(i, j, 0); }
	int ans;
	for(int i = 0 ; i < n ; ++i){
		REP(i_1, 1000)REP(j_1, 1000){ ed[i_1][j_1] = false; }
		point t = solve('1' + i);
		que = {};
		que.push(t);
		ans = t.step;
	}
	
	cout << ans << endl;

	return 0;
}