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<string> 
using namespace std;
int n,m,k,f[4][2]={0,1,0,-1,1,0,-1,0},maxx=-9999;
char map[1010][1010];
int head=1,tail=1,sx,sy;
int dp[1010][1010];
struct node{
	int x,y,sum,ans;
}a[1000010];
int main()
{
	cin>>n>>m>>k;
	string s[1010];
	for(int i=1;i<=n;i++)
	cin>>s[i];
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=m;j++)
		{
			map[i][j]=s[i][j];
			if(map[i][j]=='S')
			{
				sx=i;
				sy=j;
			}
		}
	}
	a[head].x=sx;
	a[head].y=sy;
	a[head].sum=1;
	a[head].ans=1;
	dp[sx][sy]=1;
	tail++;
	while(head<tail) 
	{
		int flag=0;
		int nx=a[head].x,ny=a[head].y;
		if(a[head].ans==head)
		{
			maxx=a[head].sum;
		}
		for(int i=0;i<=3;i++)
		{
			int tx=nx+f[i][0];
			int ty=ny+f[i][1];
			if(tx<1||tx>n||ty<1||ty>m||map[tx][ty]=='X') continue;
			if(map[tx][ty]>='1'&&map[tx][ty]<='9') 
			{
				if(a[head].ans<map[tx][ty]-48)
				flag=1;
			}
			if(flag) continue;
			if(map[tx][ty]>='1'&&map[tx][ty]<='9')
			{
				if(a[head].sum+1<dp[tx][ty]||dp[tx][ty]==0)
				{
					a[tail].x=tx;
					a[tail].y=ty;
					a[tail].ans=a[head].ans+1;
					a[tail].sum=a[head].sum+1;
					dp[tx][ty]=a[tail].sum;
					tail++;
				}
			}
			else if(a[head].sum+1<dp[tx][ty]||dp[tx][ty]==0)
			{
				a[tail].x=tx;
				a[tail].y=ty;
				a[tail].sum=a[head].sum+1;
				dp[tx][ty]=a[tail].sum;
				tail++;
			}
		}
		head++; 
	}
	cout<<head-1;
	return 0;
/*
4 5 2
.X..1
....X
.XX.S
.2.X.
*/
}

C++: #include <iostream>
#include <queue>
#include <string>
#include <set>
using namespace std;

const int MAX_H = 1005;
const int MAX_W = 1005;

string all[MAX_H];
int dx[4] = { 1, 0, -1, 0 };
int dy[4] = { 0, 1, 0, -1 };
int h, w;
int n;
int sx, sy;
typedef pair<int ,int> P;

int bfs(char target){
	set<P> s;
	queue<P> q1;
	queue<int> q2;
	q1.push(P(sy, sx));
	q2.push(0);
	while (!q1.empty()){
		P p = q1.front(); q1.pop();
		int t = q2.front(); q2.pop();
		s.insert(p);
		//cout << p.first << " " << p.second <<" "<<t<< endl;
		for (int i = 0; i < 4; ++i){
			int y = p.first + dy[i], x = p.second + dx[i];
			if (x >= 0 && x < w &&y >= 0 && y < h && all[y][x] != 'X'){
				if (s.count(P(y,x))){
					continue;
				}
				if (all[y][x] == target){
					all[y][x] = '.';
					sx = x, sy = y;
					return t + 1;
				}
				else{
					q1.push(P(y, x));
					q2.push(t + 1);
				}
			}
		}
	}
}

void solve(){
	int ans = 0;
	char t = '1';
	for (int i = 0; i < n;++i){
		ans += bfs(t);
		++t;
	}
	cout << ans << endl;
}

int main(){
	cin >> h >> w >> n;
	for (int i = 0; i < h; ++i){
		cin >> all[i];
		for (int j = 0; j < w; ++j){
			if (all[i][j] == 'S'){
				sx = j, sy = i;
				all[i][j] = '.';
			}
		}
	}
	solve();
	return 0;
}

C++: #include <cstdio>
#include <queue>
using namespace std;

int H, M, N;
int go[4][2];
bool K[1002][1002];
bool flg[1002][1002];
int score[1002][1002];
int C[11][2];
int ans = 0;

struct Tops{
  int tx, ty, co;
  
  Tops(int x, int y, int c){
    tx = x;
    ty = y;
    co = c;
  }
};

queue<Tops> que;

int cal(int x, int y){
  while(!que.empty()){
    Tops t = que.front();
    que.pop();
    flg[t.tx][t.ty] = false;
    if(t.tx == x && t.ty == y){
      return t.co;
    }
    for(int i = 0; i < 4; i++){
      if(flg[t.tx + go[i][0]][t.ty + go[i][1]]){
        que.push(Tops(t.tx + go[i][0], t.ty + go[i][1], t.co + 1));
      }
    }
  }
  return 2147483647;
}

int main(){
  
  go[0][0] = 1;
  go[0][1] = 0;
  go[1][0] = 0;
  go[1][1] = -1;
  go[2][0] = -1;
  go[2][1] = 0;
  go[3][0] = 0;
  go[3][1] = 1;
  
  for(int i = 0; i <= H + 1; i++){
    for(int j = 0; j <= M + 1; j++){
      score[i][j] = 2147483640;
      flg[i][j] = false;
      K[i][j] = false;
    }
  }
  
  scanf("%d%d%d", &H, &M, &N);
  
  for(int i = 0; i < H; i++){
    char str[M + 1];
    scanf("%s", str);
    for(int j = 0; j < M; j++){
      if(str[j] == '.'){
        K[i + 1][j + 1] = true;
      }else if(str[j] == 'X'){
        K[i + 1][j + 1] = false;
      }else if(str[j] == 'S'){
        C[0][0] = i + 1;
        C[0][1] = j + 1;
        K[i + 1][j + 1] = true;
      }else{
        C[str[j] - '0'][0] = i + 1;
        C[str[j] - '0'][1] = j + 1;
        K[i + 1][j + 1] = true;
      }
    }
  }
  
  for(int i = 0; i < N; i++){
    for(int j = 0; j <= M + 1; j++){
      for(int k = 0; k <= H + 1; k++){
        flg[j][k] = K[j][k];
      }
    }
    while(!que.empty()){
      que.pop();
    }
    que.push(Tops(C[i + 1][0], C[i + 1][1], 0));
    int aa = cal(C[i][0], C[i][1]);
    ans += aa;
  }
  
  printf("%d\n", ans);
  
  return 0;
}

C++: #define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <vector>
#include <set>
#include <map>
#include <sstream>
#include <string>
#include <cstdio>
#include <stack>
#include <queue>
#include <algorithm>
#include <numeric>
#include <functional>
#include <cstring>
#include <tuple>
#include <utility>
#include <list>
#include <cmath>
#include <unordered_map>

using namespace std;

typedef long long LL;
typedef vector<int> Array;
typedef pair<int, int> P;

const int INF = 1 << 29;
const LL MOD = 100000;
#define rep(i,n) for(int i=0;i<(int)n;++i)
#define all(c) (c).begin(), (c).end()

struct edge{ int to, cost; edge(int t, int c) :to(t), cost(c){} };

int main()
{
	//while (cin >> n)
	stringstream ss;
	//ss << "result" << i + 1 << ".txt";
	//FILE* fp_out = freopen(ss.str().c_str(), "w", stdout);

	int h, w, n;
	while (cin >> h >> w >> n && h)
	{
		vector<vector<char>> stage(h, vector<char>(w));
		vector<P> cheese(n + 1);
		rep(i, h) rep(j, w)
		{
			char c; cin >> c;
			stage[i][j] = c;
			if (c == 'S') cheese[0] = P(i, j);
			if (1 <= c - '0' && c - '0' <= 9) cheese[c - '0'] = P(i, j);
		}

		int ans = 0;
		vector<int> dr = { -1, 0, 1, 0 };
		vector<int> dc = { 0, 1, 0, -1 };
		rep(i, n)
		{
			P from = cheese[i], to = cheese[i + 1];
			typedef pair<P, int> PI;
			queue<PI> que;
			vector<vector<bool>> visited(h, vector<bool>(w));
			que.emplace(from, 0);
			while (!que.empty())
			{
				PI pi = que.front(); que.pop();
				P p = pi.first; int len = pi.second;

				if (p == to)
				{
					ans += len;
					break;
				}

				visited[p.first][p.second] = true;
				rep(k, 4)
				{
					int nr = dr[k] + p.first, nc = dc[k] + p.second;
					if (nr < 0 || nr >= h || nc < 0 || nc >= w ||
						stage[nr][nc] == 'X' || visited[nr][nc]) continue;
					
					que.emplace(P(nr, nc), len + 1);
				}
			}
		}

		cout << ans << endl;
	}

	return 0;
}