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<vector>

using namespace std;

int nowS = 0;
int x, y, n;
int mp[1000][1000] = {};
int k[4] = {1, -1, 0, 0};
int h[4] = {0, 0, 1, -1};
int cx[9] = {};
int cy[9] = {};
vector<int> bufX, bufY, bufD;

bool search(int xx, int yy, int dd) {
	bufX.erase(bufX.begin());
	bufY.erase(bufY.begin());
	bufD.erase(bufD.begin());

	for (int i = 0; i < 4; i++) {
		if (xx + k[i] < 0 || xx + k[i] >= x || yy + h[i] < 0 || yy + h[i] >= y)
			continue;
		if (mp[yy + h[i]][xx + k[i]] != 0) {
			continue;
		}
		if (cx[nowS] == xx + k[i] && cy[nowS] == yy + h[i]) {
			nowS++;
			bufX.clear();
			bufY.clear();
			bufD.clear();
			if (nowS == n) {
				cout << dd + 1 << endl;
				return true;
			}
			else {
				bufX.push_back(xx + k[i]);
				bufY.push_back(yy + h[i]);
				bufD.push_back(dd + 1);
			}
			return false;
		}
		if(mp[yy + h[i]][xx + k[i]] == 0){
			bufX.push_back(xx + k[i]);
			bufY.push_back(yy + h[i]);
			bufD.push_back(dd + 1);
		}
	}
	return false;
}

int main() {
	int ch = 0;
	cin >> y >> x >> n;
	for (int i = 0; i < y; i++) {
		char c[1001];
		cin >> c;
		for (int j = 0; j < x; j++) {
			if(c[j] == 'X')
				mp[i][j] = -1;
			else if(c[j] == 'S'){
				bufX.push_back(j);
				bufY.push_back(i);
				bufD.push_back(0);
				mp[i][j] = 0;
			}	
			else {
				mp[i][j] = 0;
			}
			if (c[j] >= 48 && c[j] <= 57) {
				int m;
				m = c[j] - 49;
				cx[m] = j;
				cy[m] = i;		
				ch++;
			}
		}
	}
	

	while(!search(bufX[0], bufY[0], bufD[0])){}

	return 0;
}

C++: #include <bits/stdc++.h>

using namespace std;
typedef long long int ll;
typedef pair<int, int> P;
typedef pair<ll, ll> Pll;
typedef vector<int> Vi;
typedef tuple<int, int, int> T;
#define FOR(i,s,x) for(int i=s;i<(int)(x);i++)
#define REP(i,x) FOR(i,0,x)
#define ALL(c) c.begin(), c.end()
#define DUMP( x ) cerr << #x << " = " << ( x ) << endl

const int dr[4] = {-1, 0, 1, 0};
const int dc[4] = {0, 1, 0, -1};

int H, W, N;
string town[1024];
int dist[10][1024][1024];

inline bool in(int r, int c) {
  return 0 <= r && r < H && 0 <= c && c < W;
}

int main() {
  // use scanf in CodeForces!
  cin.tie(0);
  ios_base::sync_with_stdio(false);

  cin >> H >> W >> N;
  REP(i, H) cin >> town[i];
  int sr = 0, sc = 0;
  REP(i, H) REP(j, W) {
    if (town[i][j] == 'S') {
      sr = i, sc = j;
      break;
    }
  }

  int ans = 0;
  REP(i, N) {
    queue<T> que;
    que.push(T(sr, sc, 1));
    while (!que.empty()) {
      int r, c, d;
      tie(r, c, d) = que.front(); que.pop();
      if (dist[i][r][c]) continue;
      dist[i][r][c] = d;
      if ('1' <= town[r][c] && town[r][c] <= '9' && town[r][c] - '0' == i+1) {
	ans += d-1;
	sr = r, sc = c;
	break;
      }
      REP(j, 4) {
	int nr = r + dr[j], nc = c + dc[j];
	if (in(nr, nc) && town[nr][nc] != 'X' && !dist[i][nr][nc]) {
	  que.push(T(nr, nc, d+1));
	}
      }
    }
  }

  cout << ans << endl;      
  return 0;
}

C++: #include<cstdio>
#include<algorithm>
#include<queue>
#include <iostream>
#define inf 1000000
using namespace std;
int H,W,N,x0,y0;
char map[1005][1005];int d[1005][1005];
int dx[4]={-1,0,1,0};
int dy[4]={0,-1,0,1};
typedef pair<int,int>P;
struct position
{
	int rx,ry,e;
}xy[9];
bool comp(const position a,const position b)
{
	return a.e<b.e;
}
int bfs(int sx,int sy,int gx,int gy)
{
	int tx,ty;
	queue<P>q;

	for(int i=0;i<H;i++)
	{
		for(int j=0;j<W;j++)
		d[i][j]=inf;
	}
	q.push(P(sx,sy));
	d[sx][sy]=0;
	while(!q.empty())
	{
		P p=q.front();
		if(p.first==gx&&p.second==gy)
		return d[p.first][p.second];
		q.pop();
		for(int i=0;i<4;i++)
		{
			tx=p.first+dx[i];
			ty=p.second+dy[i];
			if(tx>=0&&tx<H&&ty>=0&&ty<W&&map[tx][ty]!='X'&&d[tx][ty]==inf)
			{
				d[tx][ty]=d[p.first][p.second]+1;
				q.push(P(tx,ty));
			}
		}
	}
}
int main(void)
{
	while(scanf("%d%d%d",&H,&W,&N)==3)
	{
		int x1[9],y1[9];
		for(int i=0;i<H;i++)
		scanf("%s",&map[i]);
		int t=0;
		for(int i=0;i<H;i++)
		{
			for(int j=0;j<W;j++)
			{
				if(map[i][j]=='S')
				{
					x0=i;
					y0=j;
				}
				if(map[i][j]-'0'>0&&map[i][j]-'0'<=9)
				{
					xy[t].rx=i;
					xy[t].ry=j;
					xy[t].e=map[i][j]-'0';
					t++;
				}
			}
		}

		sort(xy,xy+N,comp);
		int ans=bfs(x0,y0,xy[0].rx,xy[0].ry);
		for(int i=0;i<N-1;i++)
		ans+=bfs(xy[i].rx,xy[i].ry,xy[i+1].rx,xy[i+1].ry);
		printf("%d\n",ans);
	}
	return 0;
}

C++: #include <bits/stdc++.h>
using namespace std;

typedef pair<int,int> P;
#define FOR(i,a,b) for(int i=(a);i<(int)(b);i++)
#define rep(i,n) FOR(i,0,n)
#define F first
#define S second

const int M = 1024;
const int INF = 114514810;
int h,w,n;
char f[M][M];
int d[M][M];
int dx[]={1,0,-1,0};
int dy[]={0,1,0,-1};
vector<P> cheese(12);

void init() {
    rep(y,M) rep(x,M) f[y][x] = '$';
    cheese.clear();
}

bool ng(int x, int y) {
    return (x<0 or w<=x or y<0 or h<=y);
}

int bfs(P s, P g) {
    int gx=g.F, gy=g.S;
    queue<P> Q;
    rep(y,M) rep(x,M) d[y][x] = INF;
    Q.push(s);
    d[s.S][s.F] = 0;

    while(Q.size()) {
        P p = Q.front(); Q.pop();
        if(p.F==gx and p.S==gy) break;

        rep(i,4) {
            int nx = p.F + dx[i], ny = p.S + dy[i];
            if(ng(nx,ny) or f[ny][nx]=='X' or d[ny][nx]<INF) continue;
            d[ny][nx] = d[p.S][p.F] + 1;
            Q.push(P(nx,ny));
        }
    }

    return d[gy][gx];
}

int main() {
    while(cin>>h>>w>>n) {
        init();
        rep(y,h) rep(x,w) {
            cin >> f[y][x];
            char c = f[y][x];
            if(c!='.' and c!='S' and c!='X') cheese[c-'0'] = make_pair(x,y);
            if(c == 'S') cheese[0] = make_pair(x,y);
        }

        int ans = 0;
        rep(i,n) ans += bfs(cheese[i], cheese[i+1]);
        cout << ans << endl;
    }

    return 0;
}