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 <algorithm>
#include <queue>

using namespace std;

struct P{
  int s;
  int t;
};

struct P2{
  int s;
  int t;
  int c;
};

int ds[4] = {0, 1, 0, -1}, dt[4] = {1, 0, -1, 0};

int bfs(char ch[1001][1001], P st, P go, int w, int h)
{
  bool fa[1001][1001];
  fill(&fa[0][0], &fa[1000][1000],  true);
  P2 p, q;
  queue<P2> que;
  p.s = st.s;
  p.t = st.t;
  p.c = 0;
  que.push(p);
  int c = 0;
  while(!que.empty()){
    p = que.front();
    que.pop();

    if(p.s == go.s && p.t == go.t){
      c = p.c;
      break;
    }

    for(int i = 0; i < 4; i++){
      q.s = p.s + ds[i];
      q.t = p.t + dt[i];
      if(q.s >= 0 && q.s < h && q.t >= 0 && q.t < w){
	if(fa[q.s][q.t] && ch[q.s][q.t] != 'X'){
	  fa[q.s][q.t] = false;
	  q.c = p.c + 1;
	  que.push(q);
	}
      }
    }
  }

  return c;
}

int main()
{
  int w, h, n, c;
  char ch[1001][1001];
  P pa[10];

  while(cin>>h>>w>>n && h && w && n){
    for(int i = 0; i < h; i++){
      for(int j = 0; j < w; j++){
	cin >> ch[i][j];
	if(ch[i][j] == 'S'){
	  pa[0].s = i;
	  pa[0].t = j;
	} else if(ch[i][j] != '.' || ch[i][j] != 'X'){
	  pa[(int)(ch[i][j]-'0')].s = i;
	  pa[(int)(ch[i][j]-'0')].t = j;
	}
      }
    }
    c = 0;

    for(int i = 0; i < n; i++){
      c += bfs(ch, pa[i], pa[i+1], w, h);
    }

    cout << c << endl;
  }

  return 0;
}

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

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

struct POS {int x, y;};

int main() {
	char map[1002][1002];
	static int smp[1002][1002];
	int h, w, n, c=0, ans, x, y; POS p;
	queue< pair<int, POS> > q;
	cin >> h >> w >> n;
	for(int i=0; i<h+2; ++i) for(int j=0; j<w+2; ++j) {
		map[i][j] = 'X'; smp[i][j] = 100;
	}
	for(int i=1; i<=h; ++i) for(int j=1; j<=w; ++j) {
		cin >> map[i][j]; smp[i][j] = 0;
		if(map[i][j]=='S') {
			map[i][j] = '.'; x = j; y = i;
		}
	}
	p.x = x; p.y = y;
	q.push( pair<int, POS>(0, p) );
	while(c<n) {
		ans = q.front().first;
		x = q.front().second.x; y = q.front().second.y;
		q.pop();
		smp[y][x] = c+1;
		if(map[y][x]=='1'+c) {
			c++;
			while(!q.empty()) q.pop();
		}
		for(int i=0; i<4; ++i) {
			if(map[y+dy[i]][x+dx[i]]!='X'&&smp[y+dy[i]][x+dx[i]]<c+1) {
				p.x = x+dx[i]; p.y = y+dy[i];
				q.push(pair<int, POS>(ans+1, p));
			}
		}
	}
	cout << ans << endl;
	return 0;
}

C++: //C++14 (Clang 3.8.0)

#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <string>
#define rp(i,a,b) for(int (i)=(int)(a);i<(int)(b);++i)
using namespace std;
typedef pair<int ,int> P;
int d[1001][1001],movex[]={0,0,-1,1},movey[]={1,-1,0,0};
char cc[]={'1','2','3','4','5','6','7','8','9'},a[1001][1001];
int h,w;
int nx,ny;
int bfs(int sx,int sy,char goal){
    queue<P> que;
    for(int i=0;i<h;i++){
        for(int j=0;j<w;j++){
            d[i][j]=-1;
        }
    }
    que.push(P(sx,sy));
    d[sx][sy]=0;
    int dis;
    while(que.size()){
        P p = que.front();que.pop();
        if(a[p.first][p.second]==goal) {nx=p.first;ny=p.second;return d[p.first][p.second];}
        for(int i = 0; i < 4; i++){
            int x=p.first+movex[i],y=p.second+movey[i];
            if(0<=x and x<h and 0<=y and y<w and d[x][y]==-1 and a[x][y]!='X'){
                que.push(P(x,y));
                d[x][y]=d[p.first][p.second]+1;
            }
        }
    }
    
}

int main(){
    int n;
    cin>>h>>w>>n;
    int x,y;
    for(int i=0;i<h;i++){
        for(int j=0;j<w;j++){
            cin>>a[i][j];
            if(a[i][j]=='S'){nx=i;ny=j;}
        }
    }
    int ans=0;
    for(int i=0;i<n;i++){
        ans+=bfs(nx,ny,cc[i]);
    }
    cout<<ans<<endl;

}

C++: 
#include <cstdio>
#include <queue>
#include <limits.h>
#include <cstring>
using namespace std;

typedef pair<int, int> P;
const int MAXN = 1010;
char map[MAXN][MAXN];
int n, m, t, sx, sy, ex, ey;
int d[MAXN][MAXN];
int dir[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1} };
P a[15];

int bfs()
{
    queue<P> q;
    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < m; j++)
        {
            d[i][j] = INT_MAX;
        }
    }
    d[sx][sy] = 0;
    q.push(P(sx, sy));
    while(!q.empty())
    {
        P p = q.front();  q.pop();
        if(p.first == ex && p.second == ey)
            break;
        for(int i = 0; i < 4; i++)
        {
            int x = p.first + dir[i][0];
            int y = p.second + dir[i][1];
            if(x >= 0 && x < n && y >= 0 && y < m
               && 'X' != map[x][y] && INT_MAX == d[x][y])
               {
                   q.push(P(x, y));
                   d[x][y] = d[p.first][p.second] + 1;
               }
        }
    }
    return d[ex][ey];
}

int main()
{
    scanf("%d%d%d", &n, &m, &t);
    getchar();
    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < m; j++)
        {
            scanf("%c", &map[i][j]);
            if('S' == map[i][j])
            {
                a[0] = P(i, j);
            }
            else
            {
                if('.' != map[i][j] && 'X' != map[i][j])
                {
                    a[map[i][j] - '0'] = P(i, j);
                }
            }
        }
        getchar();
    }
    int ans = 0;
    for(int i = 1; i <= t; i++)
    {
        sx = a[i-1].first;
        sy = a[i-1].second;
        ex = a[i].first;
        ey = a[i].second;
        ans += bfs();
    }
    printf("%d\n", ans);
    return 0;
}