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 <iostream>
#include <queue>
#define ROP(i,n) for(int i=0;i<n;i++)
#define ROPP(i,n) for(int i=1;i<=n;i++)
#define INF 999999999
using namespace std;
typedef pair<int,int> P;
int N,M,G,gx[10],gy[10];
char MAP[1000][1000+1];
int DX[4]={1,0,-1,0},DY[4]={0,1,0,-1},FAR[1000][1000+1];
int BFS(int u){
  queue<P> que;
  ROPP(i,N){ROPP(j,M) FAR[j][i]=INF;}
  que.push(P(gx[u],gy[u]));
  FAR[gx[u]][gy[u]]=0;
  while(que.size()){
    P p=que.front();que.pop();
    if(p.first==gx[u+1]&&p.second==gy[u+1]) break;
    ROP(i,4){
      int nx=p.first+DX[i],ny=p.second+DY[i];
      if(1<=nx&&nx<=M&&1<=ny&&ny<=N
        &&MAP[nx][ny]!='X'&&FAR[nx][ny]==INF){
        que.push(P(nx,ny));
        FAR[nx][ny]=FAR[p.first][p.second]+1;
      }
    }
  }
  return FAR[gx[u+1]][gy[u+1]];
}
void solve(){
  int res=0;
  ROP(i,G){
    res+=BFS(i);
  }
  printf("%d\n",res);
}
int main(){
  scanf("%d %d %d",&N,&M,&G);
  ROPP(i,N){
    ROP(j,M+1){
      scanf("%c",&MAP[j][i]);
      if(MAP[j][i]=='S') gx[0]=j,gy[0]=i;
      ROPP(k,G) {char l='0'+k;
      if(MAP[j][i]==l) gx[k]=j,gy[k]=i;}
    }
  }
  solve();
  return 0;
}

C++: 
#include<iostream>
#include<cstdio>
#include<deque>
#include<algorithm>

using namespace std;

typedef pair<int,int>P;

const int maxn=1e3+5;
int inf=500;

int h,w,n,sx,sy,book[maxn][maxn],goal[10],Next[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
char s[maxn][maxn];

int judge(int row,int col)
{
    if(row>=0&&row<h&&col>=0&&col<w){
        return 1;
    }
    return 0;
}

int bfs()
{
    int res=0;
    deque<P>q;
    for(int ci=0;ci<n;ci++){
        fill(book[0],book[0]+maxn*maxn,inf);
        q.push_back(P(sx,sy));
        book[sx][sy]=0;
        while(!q.empty()){
            int x=q.front().first;
            int y=q.front().second;
            q.pop_front();
            if((int)s[x][y]==49+ci){
                goal[ci]=book[x][y];
                sx=x;
                sy=y;
                break;
            }
            for(int i=0;i<4;i++){
                int nx=x+Next[i][0];
                int ny=x+Next[i][1];
                if(s[nx][ny]!='X'&&judge(nx,ny)&&book[nx][ny]==inf){
                    q.push_back(P(nx,ny));
                    book[nx][ny]=book[x][y]+1;
                }
            }
        }
        q.clear();
        res+=goal[ci];
    }
    return res;
}

int main()
{
    cin>>h>>w>>n;
    for(int i=0;i<h;i++){
        for(int j=0;j<w;j++){
            cin>>s[i][j];
            if(s[i][j]=='S'){
                sx=i;
                sy=j;
            }
        }
    }
    int res=bfs();
    cout<<res<<endl;
    return 0;
}

C++: #include<stdio.h>
#include<iostream>
#include<queue>
#include<string.h>
using namespace std;
struct PP{
	int x;
	int y;
	int Z;
	int c;
};
char s[1002][1002],C[11]={"0123456789"};
int D[1002][1002];
int A[1002][1002],d;
int main(){
	PP S;
	queue<PP> P;
	int  w,h;
	int d=0,i=0,j=0,l=-1;
	int x[4]={ 1, 0,-1,0};
	int y[4]={ 0 ,1,0,-1};
	scanf("%d %d %d",&h,&w,&d);
//	memset(A,0,sizeof(A));
   memset(D,0,sizeof(D));
		for(i=0;i<h;i++){
		scanf("%s",s[i]);
	}
	for(i=0;i<h;i++){
		for(j=0;j<w;j++){
		if(s[i][j]=='S'){
			S.x=j;
			S.y=i;
			S.Z=0;
			S.c=1;
			A[S.y][S.x]=1;
			P.push(S);
		}
		}
	}
	while(1){
		l++;
		
		if(l==4) {
			l=0;
			P.pop();
		}
		S=P.front();

		S.x+=x[l];
		S.y+=y[l];
		S.Z++;

		if(s[S.y][S.x]=='X'||S.y==h||S.x==w||S.x==-1||S.y==-1){
		continue;
		}
//				A[S.y][S.x]=1;
		if(C[S.c]==s[S.y][S.x]){
				S.c++;
				if(S.c==d+1){
				break;
				}
				while(!P.empty()){
				P.pop();
				
				}
			//memset(A,0,sizeof(A));
			l=-1;

		} 
		P.push(S);
	}
	printf("%d\n",S.Z);
	return 0;
}

C++: // AOJ 0558
#include<iostream>
#include<cstdio>
#include<string>
#include<vector>
#include<queue>
#include<map>
#define REP(i,n) for(int i=0;i<(int)(n);i++)
#define X first
#define Y second
using namespace std;

typedef pair<int,int> P;
typedef pair<int,P> S;

int H, W, N;
const int HMAX = 1008, WMAX = 1008;
char field[HMAX][WMAX];

bool legal(P p) {
  return 0 <= p.X and p.X < W and 0 <= p.Y and p.Y < H
    and field[p.X][p.Y] != 'X';
}

const int INF = 1e7;
int dist[HMAX][WMAX];

int distance(P start, P goal) {
  priority_queue<S, vector<S>, greater<S> > que;
  REP(x,W) REP(y,H) { dist[x][y] = INF; }

  dist[start.X][start.Y] = 0;
  que.push(S(0, start));

  while (!que.empty()) {
    S state = que.top(); que.pop();
    P cur = state.second;
    if (dist[cur.X][cur.Y] < state.first) continue;
    
    const int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};
    REP(i, 4) {
      P p = P(cur.X + dx[i], cur.Y + dy[i]);
      if (legal(p) and dist[p.X][p.Y] > dist[cur.X][cur.Y] + 1) {
        dist[p.X][p.Y] = dist[cur.X][cur.Y] + 1;
        que.push(S(dist[p.X][p.Y], p));
      }
    }
  }
  return dist[goal.X][goal.Y];
}

P search(char c) {
  REP(y, H) REP(x, W) {
    if (field[x][y] == c)
      return P(x, y);
  }
}

int solve() {
  int ans = 0;
  P start = search('S');
  for (int i = 1; i <= N; i++) {
    P goal = search('0' + i);
    ans += distance(start, goal);
    start = goal;
  }
  return ans;
}

int main() {
  cin >> H >> W >> N;
  REP(y, H) {
    string row;
    cin >> row;
    REP(x, W) {
      field[x][y] = row[x];
    }
  }

  cout << solve() << endl;
}

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

#define INF 20000000

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

typedef pair<int, int> P;

int main() {
	char map[1002][1002];
	static int smp[1002][1002];
	int h, w, n, c=0, x, y, ans=0;
	queue<P> 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] = INF;
	}
	for(int i=1; i<=h; ++i) for(int j=1; j<=w; ++j) {
		cin >> map[i][j]; smp[i][j] = INF;
		if(map[i][j]=='S') {x = j; y = i;}
	}
	q.push(P(x, y)); smp[y][x] = 0;
	while(1) {
		x = q.front().first;
		y = q.front().second;
		q.pop();
		if(map[y][x]=='1'+c) {
			ans += smp[y][x]; c++;
			if(c==n) break;
			while(!q.empty()) q.pop();
			for(int i=1; i<=h; ++i) for(int j=1; j<=w; ++j) smp[i][j] = INF;
			smp[y][x] = 0;
		}
		for(int i=0; i<4; ++i) {
			if(map[y+dy[i]][x+dx[i]]!='X'&&smp[y+dy[i]][x+dx[i]]==INF) {
				q.push(P(x+dx[i], y+dy[i]));
				smp[y+dy[i]][x+dx[i]] = smp[y][x]+1;
			}
		}
	}
	cout << ans << endl;
	return 0;
}