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 <cstdio>
#include <queue>
#include <tuple>

#define MAX_W 1010
#define MAX_H 1010

using namespace std;

int w, h, n;
char sections[MAX_H][MAX_W];
bool visited[MAX_H][MAX_W];
int dx[] = {1, 0, -1, 0};
int dy[] = {0, -1, 0, 1};

tuple<int, int, int> bfs(queue<tuple<int, int, int> > &que, int hp) {
  if (que.empty()) return make_tuple(-1, -1, -1);
  int x, y, d;
  tie(x, y, d) = que.front(); que.pop();
  visited[y][x] = true;
  for (int i = 0; i < 4; ++i) {
    int nx = x + dx[i], ny = y + dy[i];
    if ((0 <= nx && nx < w && 0 <= ny && ny < h) &&
        (!visited[ny][nx] && sections[ny][nx] != 'X')) {
      if (sections[ny][nx] == ('0' + hp))
        return make_tuple(nx, ny, d + 1);
      else
        que.push(make_tuple(nx, ny, d + 1));
    }
  }
  return bfs(que, hp);
}

int main() {
  scanf("%d %d %d", &h, &w, &n);
  for (int i = 0; i < h; ++i) {
    scanf("%s", sections[i]);
  }

  int sx, sy;
  for (int i = 0; i < h; ++i) {
    for (int j = 0; j < w; ++j) {
      if (sections[i][j] == 'S') {
        sx = j; sy = i;
      }
    }
  }

  int ans = 0;
  queue<tuple<int, int, int> > que;
  que.push(make_tuple(sx, sy, 0));
  for (int hp = 1; hp <= n; ++hp) {
    for (int i = 0; i < h; ++i) {
      for (int j = 0; j < w; ++j) {
        visited[i][j] = false;
      }
    }
    int x, y, d;
    tie(x, y, d) = bfs(que, hp);
    ans += d;
    que = queue<tuple<int, int, int> >();
    que.push(make_tuple(x, y, 0));
  }
  printf("%d\n", ans);
  
  return 0;
}

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

class Point{
public:
  int x,y,c;
  Point(int x = 0,int y = 0,int c = 0):x(x),y(y),c(c){}
};

int main(){
  int i,j,k,l,n,h,w,x[10],y[10],ans;
  bool a[1000][1000];
  string str;
  while(cin >> h >> w >> n){

    for(i=0;i<h;i++){
      cin >> str;
      for(j=0;j<w;j++){
	if(str[j] == 'S'){
	  a[i][j] = false;
	  x[0] = j;
	  y[0] = i;
	}
	else if(str[j] == '.') a[i][j] = false;
	else if(str[j] == 'X') a[i][j] = true;
	else{
	  a[i][j] = false;
	  int c = str[j] - '0';
	  x[c] = j;
	  y[c] = i;
	}
      }
    }

    ans = 0;
    for(i=0;i<n;i++){
      Point u,v;
      queue<Point> Q;
      bool f[1000][1000];

      for(j=0;j<h;j++){
	for(k=0;k<w;k++) f[j][k] = false;
      }

      u.x = x[i];
      u.y = y[i];

      Q.push(u);
      while(!Q.empty()){
	u = Q.front();
	Q.pop();
	f[u.y][u.x] = true;
	if(u.x == x[i+1] && u.y == y[i+1]){
	  ans += u.c;
	  break;
	}

	int dx[4] = {-1,0,1,0};
	int dy[4] = {0,1,0,-1};
	for(j=0;j<4;j++){
	  v = u;
	  v.x += dx[j];
	  v.y += dy[j];
	  if(v.x >= 0 && v.x < w && v.y >= 0 && v.y < h && !f[v.y][v.x] && !a[v.y][v.x]){
	      v.c++;
	   Q.push(v);
	   f[v.y][v.x] = true;
          }
         }
       }
     }

    cout << ans << endl;

  }
  return 0;
}

C++: #include<cstdio>
#include<cstring>
#include<queue>
#define maxn 1002
#define maxc 10
using namespace std;
struct point{
    int r,c;
};
char graph[maxn][maxn];
int len[maxn][maxn];
bool mark[maxn][maxn];
point node[maxc];
int dir[4][2]={1,0,-1,0,0,1,0,-1};
int main(void){
    int h,w,cheese,tr,tc,answer=0;
    scanf("%d%d%d",&h,&w,&cheese);
    memset(graph,0,sizeof(graph));
    memset(node,0,sizeof(node));
    for(int i=1;i<=h;i++) for(int j=1;j<=w;j++){
        do scanf("%c",&graph[i][j]);
        while(graph[i][j]==' ' || graph[i][j]=='\n');
        if(graph[i][j]>='0' && graph[i][j]<='9'){
            node[graph[i][j]-'0'].r=i;
            node[graph[i][j]-'0'].c=j;
        }
        else if(graph[i][j]=='S'){
            node[0].r=i;
            node[0].c=j;
        }
    }
    for(int cnt=0;cnt<cheese;cnt++){
        memset(len,0,sizeof(len));
        memset(mark,false,sizeof(mark));
        for(int i=0;i<=h+1;i++){mark[i][0]=true;mark[i][w+1]=true;}
        for(int j=0;j<=w+1;j++){mark[0][j]=true;mark[h+1][j]=true;}
        queue<point> q;
        q.push(node[cnt]);
        len[node[cnt].r][node[cnt].c]=0;
        point ongo,togo;
        while(!q.empty()){
            ongo=q.front();
            q.pop();
            if(mark[ongo.r][ongo.c]) continue;
            mark[ongo.r][ongo.c]=true;
            if(ongo.r==node[cnt+1].r && ongo.c==node[cnt+1].c){
                answer+=len[ongo.r][ongo.c];
                break;
            }
            for(int i=0;i<4;i++){
                togo.r=ongo.r+dir[i][0];togo.c=ongo.c+dir[i][1];
                if(mark[togo.r][togo.c]==false && graph[togo.r][togo.c]!='X'){
                    len[togo.r][togo.c]=len[ongo.r][ongo.c]+1;
                    q.push(togo);
                }
            }
        }
    }
    printf("%d\n",answer);
    return 0;
}

C++: #include <iostream>
#include <string>
#include <queue>
#include <vector>
#include <set>
#include <map>
#include <algorithm>
#include <utility>
#include <iomanip>

#define ll long long int
#define pb push_back
#define mk make_pair
#define pq priority_queue

using namespace std;
typedef pair<int, int> P;
typedef pair<ll, int> Pl;
const int inf = 1e9;
const ll linf = 1LL << 50;

int h, w, n;
int sx, sy;
int c[1001][1001];
int x[10];
int y[10];
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, -1, 0, 1};
int used[1001][1001];

int dfs(int stx, int sty, int gx, int gy){
		queue<P> q;
		for(int i = 0; i < h; i++){
				for(int j = 0; j < w; j++)used[i][j] = -1;
		}
		used[stx][sty] = 0;
		q.push(mk(stx, sty));
		while(!q.empty()){
				P p = q.front(); q.pop();
				int xx = p.first;
				int yy = p.second;
				if(xx == gx && yy == gy){
						return used[gx][gy];
				}
				for(int i = 0; i < 4; i++){
						int nx = xx + dx[i];
						int ny = yy + dy[i];
						if(nx >= 0 && nx < h && ny >= 0 && ny < w && used[nx][ny] == -1 && c[nx][ny] == 0){
								used[nx][ny] = used[xx][yy] + 1;
								q.push(mk(nx, ny));
						}
				}
		}
		return -1;
}

int main(int argc, char const* argv[])
{
	cin >> h >> w >> n;
	for(int i = 0; i < h; i++){
			string s;
			cin >> s;
			for(int j = 0; j < w; j++){
					if(s[j] == '.')c[i][j] = 0;
					else if(s[j] == 'X')c[i][j] = -1;
					else if(s[j] == 'S'){
							sx = i;
							sy = j;
							c[i][j] = 0;
					}
					else{
							x[s[j] - '1'] = i;
							y[s[j] - '1'] = j;
							c[i][j] = 0;
					}
			}
	}
	int res = 0;
	for(int i = 0; i < n; i++){
			if(i == 0)res += dfs(sx, sy, x[0], y[0]);
			else res += dfs(x[i-1], y[i-1], x[i], y[i]);
	}
	cout << res << endl;
	return 0;
}