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 <vector>
#define MAX 1000

using namespace std;

const int INF = 1000000;

typedef pair<int,int> P;

int n,m;
char cheese[MAX+1][MAX+1];
 
int bfs(int sy,int sx,int gy,int gx){
    
  int dx[4]={1,0,-1,0};
  int dy[4]={0,1,0,-1};
  int d[MAX][MAX];
  queue<P> q;
     
    for( int i = 0 ; i < n ; i++ )
        for( int j = 0 ; j < m ; j++ )
            d[i][j] = INF;
     
    q.push( P(sy , sx) );
    d[sy][sx] = 0;
     
    while( q.size() ){
        P p = q.front(); 
	q.pop();

        if(p.first == gy && p.second == gx) break;
	
        for(int i = 0 ; i < 4 ; i++){
	  int x = p.first + dx[i];
	  int y = p.second + dy[i];
          
	  if( 0 <= x && x < n &&
	      0 <= y && y < m &&
	      d[x][y] == INF &&
	      cheese[x][y]!='X'){
	    q.push( P(x , y) );
	    d[x][y] = d[p.first][p.second] + 1;
	  }
        }
    }
    
    return d[gy][gx];
}

int main(void){

    int num;
 
    cin >> n >> m >> num;
    vector<P> v(num + 1);
     
    for( int i = 0 ; i < n ; i++ ){
        for( int j = 0 ; j < m ; j++ ){
            cin >> cheese[i][j];
            if( cheese[i][j]=='S'){
                v[0].first = i;
                v[0].second = j;
            }
            if('1' <= cheese[i][j] && cheese[i][j] <= '9'){
                v[cheese[i][j]-'0'].first = i;
                v[cheese[i][j]-'0'].second = j;
            }
        }
    }
     
    int sum = 0;
    for(int i = 1 ; i < num+1 ; i++){
        sum += bfs(v[i-1].first,v[i-1].second,v[i].first,v[i].second);
    }
    cout << sum << endl;
     
    return 0;
}

C++: #include <iostream>
#include <vector>
#include <string>
#include <set>

struct Pos {
	int x;
	int y;

	Pos(): x(-1), y(-1){}
	Pos(int _x, int _y): x(_x), y(_y){}
	Pos(const Pos& rh): x(rh.x), y(rh.y){}

	bool operator<(
		const Pos& lh
	) const {
		if(lh.y > y){
			return true;
		}else if(lh.y < y){
			return false;
		}else{
			return lh.x > x;
		}
	}
};

int main(){
	int H, W, N;
	std::cin >> H >> W >> N;

	std::vector<std::string> Map(H);

	for(int i = 0; i < H; i++){
		std::cin >> Map[i];
	}

	Pos start;
	for(int i = 0; i < H; i++){
		for(int j = 0; j < W; j++){
			if(Map[i][j] == 'S'){
				start.x = j;
				start.y = i;
				break;
			}
		}
		if(start.x != -1 && start.y != -1){
			break;
		}
	}

	int ans = 0;
	std::vector<Pos> diffs(4);
	diffs[0] = Pos(0, -1);
	diffs[1] = Pos(1, 0);
	diffs[2] = Pos(0, 1);
	diffs[3] = Pos(-1, 0);

	for(int i = 1; i <= N; i++){
		//std::cout << "i: " << i << std::endl;
		bool flg = false;
		std::vector<Pos> positions(1);
		positions[0] = start;
		std::set<Pos> known_pos;
		known_pos.insert(start);
		int count = 0;

		while(flg == false){
			std::vector<Pos> new_pos;
			for(int ii = 0; ii < positions.size(); ii++){
				Pos pos = positions[ii];
				//std::cout << "pos : (" << pos.x << ", " << pos.y << ")" << std::endl;

				for(int j = 0; j < 4; j++){
					Pos d = diffs[j];
					int y = pos.y + d.y;
					int x = pos.x + d.x; 
					if(	y >= 0 && y < H &&
						x >= 0 && x < W &&
						Map[y][x] != 'X'){
						if(Map[y][x] - 48 == i){
							start.x = x;
							start.y = y;
							flg = true;
							break;
						}else{
							Pos p(x, y);
							if(known_pos.find(p) == known_pos.end()){
								new_pos.push_back(p);
							}
						}
					}
				}
				for(int k = 0; k < new_pos.size(); k++){
					known_pos.insert(new_pos[k]);
				}
			}
			count += 1;
			positions = new_pos;
		}
		ans += count;
	}

	std::cout << ans << std::endl;
}

C++: #include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cfloat>
#include <map>
#include <utility>
#include <set>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
#include <sstream>
#include <complex>
#include <stack>
#include <queue>
#include <cstring>
#include <sstream>
#include <cassert>
using namespace std;
static const double EPS = 1e-10;
typedef long long ll;
typedef pair<int,int> PI;
#define rep(i,n) for(int i=0;i<(int)n;++i)
#define FOR(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i)
#define ALL(c) (c).begin(), (c).end()
#define mp(a,b) make_pair(a,b)
#define pb(a) push_back(a)
int dx[]={0,1,0,-1},dy[]={1,0,-1,0};

typedef struct{
  short x,y;
  int cost;
  short ch;
}mouse;

short maxch[1000][1000];
char ku[1000][1000];
mouse t;
short cx,cy,nx,ny,ch,nch,h,w,n,cost;

main(){
  scanf("%d%d%d",&h,&w,&n);
  
  rep(i,h)scanf("%s",ku[i]);


  rep(i,h)rep(j,w){
    if(ku[i][j]=='S')cx=i,cy=j;
    maxch[i][j]=-1;
  }

  queue<mouse> Q;

  Q.push((mouse){cx,cy,0,0});
  maxch[cx][cy]=0;

  while(!Q.empty()){
    //cout<<Q.size()<<endl;
    t=Q.front();Q.pop();
    cx=t.x,cy=t.y,cost=t.cost;
    ch=t.ch;

    rep(i,4){
      nx=cx+dx[i],ny=cy+dy[i];
      if(nx<0 || nx>=h || ny<0 || ny>=w)continue;
	 if(ku[nx][ny]=='X')continue;
	 nch=ch;
	 if(ku[nx][ny]<='9' && ku[nx][ny]>='1' && ku[nx][ny]-'0'==t.ch+1){
	   nch=ch+1;
	 }

	 if(maxch[nx][ny]>=nch)continue;
	 if(nch==n){
	   printf("%d\n",cost+1);
	   return 0;
	 }
	 maxch[nx][ny]=nch;
	 Q.push((mouse){nx,ny,cost+1,nch});
    }
  }
}