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++: /*
* Filename:    aoj0558.cpp
* Desciption:  BFS
* Created:     2016-03-05
* Author:      JIngwei Xu [mail:xu_jingwei@outlook.com]
*
*/
#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<cstring>
#include<queue>
#define INT_MAX 1<<30
using namespace std;
const int INF=100000;
char s[1111];
int maze[1111][1111];
int N,H,W;
int sx,sy,ans,aim;
int d[1111][1111];
int dx[4]={1,-1,0,0},dy[4]={0,0,1,-1};
typedef pair<int,int> P;

void bfs(int x,int y){
	memset(d,-1,sizeof(d));
	queue<P> que;
	que.push(P(x,y));
	d[x][y]=0;
	int kx,ky;
	while (!que.empty())
	{
		P pp=que.front();que.pop();
		kx=pp.first;
		ky=pp.second;
		
		if(maze[kx][ky]==aim)break;
		int px,py;
		for (int i = 0; i < 4; i += 1)
		{
			px=kx+dx[i],py=ky+dy[i];
			if(px<0||py<0||px>=H||py>=W)continue;
			if(maze[px][py]==-1)continue;
			if(d[px][py]==-1){
				d[px][py]=d[kx][ky]+1;
				que.push(P(px,py));
			}
		}
	}
	sx=kx;sy=ky;
	ans+=d[kx][ky];
}
int main()
{
	scanf("%d%d%d",&H,&W,&N);
	for (int i = 0; i < H; i += 1)
	{
		scanf("%s",s);
		for (int j = 0; j < W; j += 1)
		{
			if(s[j]=='S'){
				sx=i;sy=j;
				maze[i][j]=0;
			}else if(s[j]=='.'){
				maze[i][j]=0;
			}else if(s[j]=='X'){
				maze[i][j]=-1;
			}else{
				maze[i][j]=s[j]-'0';
			}
		}
	}
	ans=0;
	aim=0;
	while (aim<N)
	{
		aim++;
		bfs(sx,sy);
	}
	cout<<ans<<endl;
	return 0;
}

C++: #include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <map>
#include <sstream>
#include <functional>
#include <numeric>
#include <cmath>
#include <cstring>
#include <cstdio>
#include <queue>
#include <stack>
#include <set>

using namespace std;

#define ALL(co) co.begin(), co.end()
#define tpl(...) make_tuple(__VA_ARGS__)

typedef long long LL;
typedef pair<int, int> P; typedef pair<int, P> IP; typedef pair<P, P> PP;
typedef vector<int> Array; typedef vector<vector<int> > Array2;
typedef vector<LL> LArray; typedef vector<P> PArray; typedef vector<string> SArray;

const int INF = 1 << 29;
const LL LINF = 1LL << 60;

inline int getInt() { int itiv; return (cin >> itiv, itiv); }
template <typename T> void readAll(vector<T>& vec) { for (int i = 0, size = vec.size(); i < size; i++) cin >> vec[i]; }
template <typename T, typename U> void readAll(vector<pair<T, U> >& vec) { for (int i = 0, size = vec.size(); i < size; i++) cin >> vec[i].first >> vec[i].second; }
template < typename T > inline string toString( const T &a ){ ostringstream oss; oss << a; return oss.str(); };
inline bool between(int min, int max, int n) { return min <= n && n <= max; }
inline bool inRange(int begin, int end, int n) { return begin <= n && n < end; }
inline bool inRange(int size, int n) { return 0 <= n && n < size; }

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


int main(void)
{
	ios::sync_with_stdio(false);
	int h, w, n;
	while(cin >> h >> w >> n && n)
	{
		SArray stage(h);
		PArray cheese(n + 1);
		for (int i = 0; i < h; i++)
		{
			cin >> stage[i];
			for (int j = 0; j < w; j++)
			{
				char c = stage[i][j];
				if(c == 'S')
				{
					cheese[0] = P(i, j);
				}
				if(inRange(10, c - '0'))
				{
					cheese[c - '0'] = P(i, j);
				}
			}
		}

		int ans = 0;
		for (int i = 0; i < n; i++)
		{
			P start = cheese[i];
			P goal = cheese[i + 1];

			vector<vector<bool>> visited(h, vector<bool>(w));
			queue<IP> que;
			que.push(IP(0, start));
			while (!que.empty())
			{
				IP ip = que.front(); que.pop();
				P p = ip.second;
				visited[p.first][p.second] = true;

				if(p == goal)
				{
					ans += ip.first;
					break;
				}

				for (int j = 0; j < 4; j++)
				{
					int nr = p.first + dr[j], nc = p.second + dc[j];
					if(!inRange(h, nr) || !inRange(w, nc) || stage[nr][nc] == 'X' || visited[nr][nc]) continue;

					que.push(IP(ip.first + 1, P(nr, nc)));
				}
			}
		}

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

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

using namespace std;

#define FOR(i,k,n) for(int i = (k); i < (n); i++)
#define REP(i,n) FOR(i,0,n)
#define INF 114514810
#define ELEM(array) (sizeof (array)/sizeof *(array))
#define MAX_N 100
#define SAFE_FREE(ptr) if( ptr != NULL ){ free(ptr); ptr = NULL; }
typedef unsigned int UINT;
typedef long long ll;
typedef queue<pair<int, int> > que;

char city[1005][1005];
int way[1005][1005];
int di[4] = { -1, 0, 0, 1 }; int dj[4] = { 0, -1, 1, 0 };

int main()
{
	int h, w, n;
	cin >> h >> w >> n;
	REP(i, h)REP(j, w)cin >> city[i][j];
	que start;
	REP(i, h)REP(j, w){
		if (city[i][j] == 'S')start.push(make_pair(i, j));
	}
	FOR(k, 1, n + 1)
	{
		REP(i, h)REP(j, w){
			if (city[i][j]-'0'==k )
			{
				start.push(make_pair(i, j));
			}
		}
	}
	int cnt = 0;

	REP(i, n)
	{
		REP(i, 1005)REP(j, 1005)way[i][j] = INF;
		que q;
		way[start.front().first][start.front().second] = 0;
		q.push(start.front());
		start.pop();
		while (1)
		{
			int tmpi = q.front().first; int tmpj = q.front().second;
			q.pop();
			if (tmpi == start.front().first&&tmpj == start.front().second)
			{
				cnt += way[tmpi][tmpj];
				break;
			}
			else
			{
				REP(i, 4){
					if (tmpi+di[i]>=0&&tmpi+di[i]<h&&tmpj+dj[i]>=0&&tmpj+dj[i]<w&&city[tmpi+di[i]][tmpj+dj[i]]!='X'&&way[tmpi+di[i]][tmpj+ dj[i]] == INF )
					{
						way[tmpi + di[i]][tmpj + dj[i]] = way[tmpi][tmpj] + 1;
						q.push(make_pair(tmpi + di[i], tmpj + dj[i]));
					}
				}
			}
			
		}
	}
	cout << cnt << endl;
	return 0;
}