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 <bits/stdc++.h>

using namespace std;
typedef long long int ll;
typedef vector<int> VI;
typedef pair<int, int> PII;
typedef pair<int, pair<int,int>> tup;
#define ALL(a) (a).begin(), (a).end()
#define RALL(a) (a).rbegin(), (a).rend()

#define EACH(i, c) \
  for (typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define SORT(c) sort((c).begin(), (c).end())

#define FOR(i, a, b) for (int i = (a); i < (b); ++i)
#define REP(i, n) FOR(i, 0, n)
const double PI = acos(-1.0);
#define CLR(a) memset((a), 0, sizeof(a))

// int tansaku[110];
// map<string,string> d;
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};

int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);
  bool  visited[1010][1010];
  char field[1010][1010];
  queue<tup> kuwa;
  int H, W, N;
  //CLR(visited);
  REP(i,W){REP(j,H) visited[i][j]=false;}
  cin >> H >> W >> N;
  REP(j, H) {
    REP(i, W) { cin >> field[i][j]; }
  }
  tup start;
  cin.ignore();
  REP(i, W) {
    REP(j, H) {
      if (field[i][j] == 'S') {
        start = {0,{i, j}};
      }
    }
  }
  kuwa.push(start);
  int ans=0;
  int cost =0;
  char cheeze='1';
  while(!kuwa.empty()){
  	tup r = kuwa.front();kuwa.pop();
  	int haba = r.first;
  	PII p = r.second;
  	visited[p.first][p.second] = true;
  	if(field[p.first][p.second]==cheeze){
      cost += haba;
  		if(cheeze-'0' == N)break;
  		cheeze++;
  		queue<tup> daisuke;
  		swap(kuwa,daisuke);
  		kuwa.push(make_pair(0,p));
      //CLR(visited);
      REP(i,W){REP(j,H) visited[i][j]=false;}

  		continue;
  	}
  	for(int i=0 ; i<4 ;i++){
          PII new_xy = {p.first + dx[i], p.second + dy[i]};
          if(0 <= new_xy.first && new_xy.first < W &&
              0 <= new_xy.second && new_xy.second < H &&
                  !visited[new_xy.first][new_xy.second] &&
                  field[new_xy.first][new_xy.second] != 'X'){
          kuwa.push(make_pair(haba+1,new_xy));
          visited[new_xy.first][new_xy.second] = true;
          }
        }
  }
  cout << cost << endl;
  return 0;
}

C++: #include <iostream>
#include <queue>
#include <climits>
#define REP(i,n) for(int i=0;i<(n);i++)
using namespace std;

typedef pair<int,int> pii;

int main()
{
  int H, W, N;
  const int dx[] = {1, 0, -1, 0}, dy[] = {0, 1, 0, -1};
  cin >> H >> W >> N;
  char map[H][W];
  int d[H][W], hp = 1;
  fill(d[0],d[H],INT_MAX);
  queue<pii> q;
  REP(i,H){
    REP(j,W){
      cin >> map[i][j];
      if(map[i][j] == 'S'){
        q.push({i,j});
        d[i][j] = 0;
      }
    }
  }
  while(!q.empty()){
    pii p = q.front();
    q.pop();
    if(map[p.first][p.second] >= '1' && map[p.first][p.second] <= '9' && hp == map[p.first][p.second]-'0') hp++;
    if(hp == N+1){
      cout << d[p.first][p.second] << endl;
      return 0;
    }
    REP(i,4){
      pii next_p = {p.first+dx[i],p.second+dy[i]};
      if(next_p.first < 0 || next_p.first >= H || next_p.second < 0 || next_p.second >= W || map[next_p.first][next_p.second] == 'X') continue;
      if(d[next_p.first][next_p.second] > d[p.first][p.second]+1){
        d[next_p.first][next_p.second] = d[p.first][p.second]+1;
        q.push(next_p);
      }
    }
  }
}

C++: #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
#include <stack>
#include <queue>

using namespace std;

struct point
{
	int x, y, step, vital;
};
const int dx[4] = {-1, 0, 0, 1};
const int dy[4] = {0, -1, 1, 0};

int H, W, N;

point search(const vector< vector<char> >& field, point start)
{
	vector< vector<bool> > isVisited(H, vector<bool>(W));
	queue<point> Que;
	Que.push(start);
	isVisited[start.y][start.x] = true;
	while (!Que.empty())
	{
		point p = Que.front();
		Que.pop();
		if (field[p.y][p.x] - '0' == p.vital)
		{
			++p.vital;
			return(p);
		}
		for (int i = 0; i < 4; ++i)
		{
			int nx = p.x + dx[i];
			int ny = p.y + dy[i];
			if (0 <= nx && nx < W && 0 <= ny && ny < H && isVisited[ny][nx] == false && field[ny][nx] != 'X')
			{
				point np;
				np.x = nx;
				np.y = ny;
				np.step = p.step + 1;
				np.vital = p.vital;
				Que.push(np);
				isVisited[ny][nx] = true;
			}
		}
	}
}

void solve()
{
	cin >> H >> W >> N;
	vector< vector<char> > field(H, vector<char>(W));
	point start;
	for (int i = 0; i < H; ++i)
	{
		for (int j = 0; j < W; ++j)
		{
			cin >> field[i][j];
			if (field[i][j] == 'S')
			{
				start.x = j;
				start.y = i;
				start.step = 0;
				start.vital = 1;
			}
		}
	}
	int sum = 0;
	while (start.vital < N + 1)
	{
		start = search(field, start);
		sum += start.step;
		start.step = 0;
	}
	cout << sum << endl;
}

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

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

using namespace std;

const int INF = 10000000;
typedef pair<int, int> P;

char field[1000][1001];
int H, W, N;
int sx, sy;
int gx, gy;

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

void input(void){
	cin >> H >> W >> N;
	for(int j = 0;j < H;j++){
		for(int i = 0;i < W;i++){
			cin >> field[i][j];
		}
	}
}

void firstcheck(void){
	for(int i = 0;i < W;i++){
		for(int j = 0;j < H;j++){
			if(field[i][j] == 'S'){
				sx = i;
				sy = j;
			}
		}
	}

	for(int i = 0;i < W;i++){
		for(int j = 0;j < H;j++){
			if(field[i][j] == '1'){
				gx = i;
				gy = j;
			}
		}
	}
}

void nextnum(void){
	sx = gx;
	sy = gy;

	for(int i = 0;i < W;i++){
		for(int j = 0;j < H;j++){
			if(field[i][j] == field[gx][gy] + 1){
				gx = i;
				gy = j;

				return ;
			}
		}
	}
}

int bfs(void){
	queue<P> que;

	for(int i = 0;i < W;i++){
		for(int j = 0;j < H;j++){
			dis[i][j] = INF; //????????§??§?????????
		}
	}

	que.push(P(sx, sy));
	dis[sx][sy] = 0; //??????????????????????????¢0???

	while(que.size()){ //que????????????????????§?????????
		P p = que.front(); //?????????????????????
		que.pop(); //???????????´??°

		if(p.first == gx && p.second == gy) break;

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

			if(0 <= nx && nx < W && 0 <= ny && ny < H && field[nx][ny] != 'X' && dis[nx][ny] == INF){
				que.push(P(nx, ny)); //????£??????????
				dis[nx][ny] = dis[p.first][p.second] + 1;
			}
		}
	}

	return dis[gx][gy];
}


int main(){
	int res = 0;
	input();

	for(int i = 0;i < N;i++){
		if(i == 0){
			firstcheck(); //????????????S,G?????????
		} else {
			nextnum(); //S, G?????´??°
		}
		res += bfs(); //?????¢?????????
	}
	cout << res << endl;

	return 0;
}