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 <stdio.h>
#include <memory.h>
#include <stdbool.h>

int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, -1, 0, 1};
int c[1000][1000];
int dat[1000][1000];
int cost[1000][1000];
int destination = 1;
int startposx, startposy;
int h, w, n;

struct QUEUE {
  int x, y;
};
QUEUE queue[1000000];
int qbegin = 0, qend = 0;

void bfsToDestination(int x, int y);
void PushQueue(int x, int y);
QUEUE PopQueue();
bool isQueueEmpty();


int main (void) {

  int i, j;

  scanf("%d%d%d", &h, &w, &n);

  for(i = 0; i < h; i++) {
    for(j = 0; j < w; j++) {
      dat[j][i] = fgetc(stdin);
      if (dat[j][i] == '\n') dat[j][i] = fgetc(stdin);
      if (dat[j][i] == 'S') {
	startposx = j; startposy = i;
	cost[j][i] = 0;
      }
    }
  }

  //for(i = 0; i < h; i++) {
  //  for(j = 0; j < w; j++) {
  //    printf("%c", dat[j][i]);
  //  }
  //  printf("\n");
  //}

  for (i = 0; i < n; i++) {
    memcpy(c, dat, sizeof(dat));
    bfsToDestination(startposx, startposy);
  }
  
  printf("%d\n", cost[startposx][startposy]);
    
  return 0;
}

void bfsToDestination(int x, int y) {

  int i;
  QUEUE ret;

  qbegin = 0; qend = 0;

  // map
  // int j;
  //printf("---map\n");
  //for(i = 0; i < h; i++) {
  //  for(j = 0; j < w; j++) {
  //    printf("%c", c[j][i]);
  //  }
  //  printf("\n");
  //}

  PushQueue(x, y);
  c[x][y] = 'X';

  while(!isQueueEmpty()) {
    ret = PopQueue();
    
    //printf("ret.x:%d ret.y:%d cost.x,y:%d\n", ret.x, ret.y, cost[ret.x][ret.y]);
    
    for (i = 0; i < 4; i++) {
      int nx = ret.x + dx[i];
      int ny = ret.y + dy[i];

      if ((nx >= 0) && (ny >= 0) && (nx < w) && (ny < h )) {
	if (c[nx][ny] != 'X') {
	  PushQueue(nx, ny);
	  cost[nx][ny] = cost[ret.x][ret.y] + 1;
	  if ((c[nx][ny] - '0') == destination) {
	    destination++;
	    startposx = nx; startposy = ny;
	    return;
	  }
	  c[nx][ny] = 'X';
	}
      }
    }
  }

}

void PushQueue(int x, int y) {
  queue[qend].x = x; queue[qend].y = y;
  qend++;
}

QUEUE PopQueue() {
  QUEUE ret;
  ret.x = queue[qbegin].x; ret.y = queue[qbegin].y;
  qbegin++;

  return ret;
}

bool isQueueEmpty() {
  if (qend == qbegin) return true;

  return false;
}

C++: #include<cstdio>
#include <iostream>
#include<algorithm>
#include<string>
#include<queue>
#include<vector>
#include<functional>
#include<cmath>
#include<map>
#include<stack>
#include<list>
#include<set>
#include<numeric>

#define MOD 1000000007

using namespace std;
typedef long long ll;
typedef pair<int, int> P;

int H, W, N;
int d[1010][1010];
char field[1010][1010];

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

int bfs(char s, char g) {
	queue<P> que;
	fill(d[0], d[1010], -1);
	for (int i = 0; i < H; i++) {
		for (int j = 0; j < W; j++) {
			if (field[i][j] == s) {
				que.push(P(i, j));
				d[i][j] = 0;
			}
		}
	}

	while (!que.empty()) {
		P p = que.front(); que.pop();
		if (field[p.first][p.second] == g)return d[p.first][p.second];

		for (int i = 0; i < 4; i++) {
			int ny = p.first + dy[i], nx = p.second + dx[i];
			if (0 <= nx && nx < W && 0 <= ny && ny < H && field[ny][nx] != 'X' &&
				d[ny][nx] == -1) {
				que.push(P(ny, nx));
				d[ny][nx] = d[p.first][p.second] + 1;
			}
		}
	}
	return -1;
}
int main()
{
	cin >> H >> W >> N;
	for (int i = 0; i < H; i++) {
		for (int j = 0; j < W; j++) {
			cin >> field[i][j];
		}
	}
	int ans = bfs('S','1');
	for (int i = 1; i < N; i++)
		ans += bfs(i + '0', i + 1 + '0');
	cout << ans << endl;
	return 0;
}

C++: #include<stdio.h>
#include<vector>
#include<queue>
#include<string.h>
#include<iostream>
#include<algorithm>
#define INF 1000000000
#define MAXN 100005
using namespace std;
int mmin=11;
int step[4][2]={0,1,0,-1,-1,0,1,0};
int a[1005][1005];int m,n,k,sx,sy;
struct node{
    int x,y,cost;
};
int bfs(int x,int y,int s)
{
    queue<node>q;
    bool vis[1005][1005]={0};
    node now={x,y,0};
    q.push(now);
    while(!q.empty())
    {
        now=q.front();q.pop();
        if(a[now.x][now.y]==s)break;
        for(int i=0;i<4;i++)
        {
            int xx=now.x+step[i][0],yy=now.y+step[i][1];
            if(!vis[xx][yy]&&a[xx][yy]!=-1){
                vis[xx][yy]=1;
                node temp={xx,yy,now.cost+1};
                q.push(temp);

            }
        }
    }
    //cout<<now.cost<<endl;
    sx=now.x;sy=now.y;
    return now.cost;
}
int main()
{
    scanf("%d%d%d",&n,&m,&k);
    memset(a,-1,sizeof(a));
    for(int i=1;i<=n;i++){
        string x;cin>>x;
        for(int j=1;j<=m;j++)
        {
            char c=x[j-1];
            if(c=='S'){a[i][j]=0;sx=i;sy=j;}
            else if(c=='X')a[i][j]=-1;
            else if(c=='.')a[i][j]=0;
            else a[i][j]=c-'0';
        }
    }
    int sum=0;
    for(int i=1;i<=k;i++)
    {
        sum+=bfs(sx,sy,i);
    }
    printf("%d\n",sum);
}

C++: #include <cstdio>
#include <iostream>
#include <queue>
#include <string.h>

using namespace std;

int W, H, N;
typedef pair<int, int> P;
queue<P> que;
char maze[1003][1003];
int timer[1003][1003];
int pos_x, pos_y;
int sh_x[4] = {0, 0, -1, 1};
int sh_y[4] = {1, -1, 0, 0};
int res = 0;
int strength = 1;

void solve() {
  que.push(P(pos_x, pos_y));

  while(que.size()) {
    P pos = que.front(); que.pop();
    if (maze[pos.second][pos.first] - '0' == strength) {
      //printf("[%d] [%d]\n", pos.second, pos.first);
      while(que.size()) que.pop();
      strength++;
      if (strength == N+1) {
        res = timer[pos.second][pos.first];
        break;
      }

      for (int i=0;i<H;i++) {
        for (int j=0;j<W;j++) {
          if (maze[i][j] == '#') maze[i][j] = '.';
        }
      }

      maze[pos.second][pos.first] = '#';
      que.push(pos);
      continue;
    }
    for (int i=0;i<4;i++) {
      int new_x = pos.first + sh_x[i];
      int new_y = pos.second + sh_y[i];
      if (new_x >= 0 && new_x < W && new_y >=0 && new_y < H && maze[new_y][new_x] != '#' && maze[new_y][new_x] != 'X') {
        //printf("Go to [%d] [%d]\n", new_y, new_x);
        que.push(P(new_x, new_y));
        if (maze[new_y][new_x] == '.') {
          maze[new_y][new_x] = '#';
        }
        timer[new_y][new_x] = timer[pos.second][pos.first] + 1;
      }
    }
  }
}

int main() {
  while (1)
  {
    scanf("%d %d %d", &H, &W, &N);
    getchar();
    if (!W && !H) {
      break;
    }
    
    for (int i = 0; i < H; i++)
    {
      fgets(maze[i], 1002, stdin);
      maze[i][W] = '#';
    }

    for (int i=0;i<H;i++) {
      for (int j=0;j<W;j++) {
        if (maze[i][j] == 'S') {
          pos_x = j;
          pos_y = i;
        }
        if (i==H-1) {
          maze[H][j] = '#';
        }
      }
    }

    solve();
    printf("%d\n", res);
    memset(timer, 0, sizeof(timer[0][0]) * H * W);
    strength = 1;
  }
  return 0;
}