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<cmath>
#include<vector>
#include<queue>
#include<iostream>
#include<algorithm>
#define debug(ARGS) cout << #ARGS << ": " << ARGS << endl;
#define ll long long

#define INF (int)1e7
#define p pair<int, int>
#define F 0
#define X -1
#define S -2

using namespace std;

int convert(char c){
  int ret;

  if('1' <= c && c <= '9') ret = c - '1' + 1;
  else if(c == '.') ret = F;
  else if(c == 'X') ret = X;
  else if(c == 'S') ret = S;
  else ret = -3;

  return ret;
}

p find_nest(vector< vector<int> > &v, int num){
  int h = v.size(), w = v[0].size();
  p ret;
  
  for(int i = 0; i < h; i++)
    for(int j = 0; j < w; j++)
      if(v[i][j] == num) ret = p(i, j);

  return ret;
}

int count_minite(vector< vector<int> > &v, int start, int end){
  int h = v.size(), w = v[0].size();
  int ret = -1;
  vector< vector<bool> > m; m.resize(h); for(int i = 0; i < h; i++) m[i].resize(w, false);
  queue< pair< p, int> > q;
  q.push(pair< p, int>(find_nest(v, start), 0));

  while(!q.empty()){
    p here = q.front().first; 
    ret = q.front().second;
    q.pop();
    int y = here.first, x = here.second;
    
    if(v[y][x] == end) break;
    else if(v[y][x] == X) continue;

    m[y][x] = true;
    
    if(x > 0 && !m[y][x-1]) q.push(pair< p, int>(p(y, x-1), ret+1));
    if(x < w - 1 && !m[y][x+1]) q.push(pair< p, int>(p(y, x+1), ret+1));
    if(y > 0 && !m[y-1][x]) q.push(pair< p, int>(p(y-1, x), ret+1));
    if(y < h - 1 && !m[y+1][x]) q.push(pair< p, int>(p(y+1, x), ret+1));
  }
  
  return ret;
}

int main(){
  int h, w, n;
  cin >> h; cin >> w; cin >> n;
  vector< vector<int> > v;  
  v.resize(h); for(int i = 0; i < h; i++)  v[i].resize(w);
  int count = 0;

  for(int i = 0; i < h; i++)
    for(int j = 0; j < w; j++){
      char c; cin >> c;
      v[i][j] = convert(c);
    }

  int start = S;  
  for(int i = 1; i <= n; i++){
    count += count_minite(v, start, i);
    start = i;
  }

  cout << count << endl;
  
  return 0;
}

C++: #include<iostream>
#include<vector>
#include<algorithm>
#include<set>
#include<queue>
#include<string>
#include<cstdio>
#include<stack>
#include<cmath>
#include<bitset>
#include<memory>
#include<memory.h>
#include<utility>
#include<map>
using namespace std;
#define FOR(i,m,n) for(i=m;i<n;i++)
#define CLR(a,b) memset(a,b,sizeof(a))
#define ROF(i,m,n) for(i=m;i>=n;i--)
#define BUG cout<<"debug"<<endl;
#define RT return
#define BK break
#define HEAP priority_queue
#define SP " "
#define rd(x) (rand()%(x))
#define lowf(a,b,c) lower_bound(a,b,c)
#define upf(a,b,c) upper_bound(a,b,c)
#define sh(a) cout<<a<<endl
typedef long long LL;
typedef vector<int> VI;
const int INF = 2147483647;
const int NEN = -INF - 1;
const LL LINF = 9223372036854775807;
int W, H, I1, J1,N;char g[1005][1005];
bool vis[1005][1005];
bool can(int x, int y)
{
	return x >= 0 && y >= 0 && x < H&&y < W&&g[x][y]!='X';
}
typedef struct node
{
	int i, j, sum;
	node()
	{
		;
	}
	node(int a, int b, int c)
	{
		i = a; j = b; sum = c;
	}
}node;
queue<node>bfs;
typedef struct pos
{
	int x,y;
}pos;
pos all[10];
int dir[4][2] = { {1,0},{-1,0},{0,1},{0,-1} };
int main()
{
	cin >> H >> W >> N;
	node temp;
	int T,i,j,ans=0;
	FOR(i, 0, H)
	{
		FOR(j, 0, W)
		{
			cin >> g[i][j];
			//scanf_s("%c", &g[i][j]);
			if (g[i][j] > '0'&&g[i][j] <='9')
			{
				all[g[i][j] - 48].x = i;
				all[g[i][j] - 48].y = j;
			}
			else if (g[i][j] == 'S')I1 = i, J1 = j;
		}
	}
	FOR(T,0,N)
	{
		CLR(vis, 0);
		while (!bfs.empty())bfs.pop();
		if(T>0)bfs.push(node(all[T].x, all[T].y, 0));
		else bfs.push(node(I1, J1, 0));
		while (!bfs.empty())
		{
			temp = bfs.front();
			bfs.pop();
			if (g[temp.i][temp.j] == T+48+1)
			{
				ans += temp.sum;
				break;
			}
			int k = 4,tx,ty;
			while (k--)
			{
				tx = temp.i + dir[k][0];
				ty = temp.j + dir[k][1];
				if (can(tx, ty) == true&&!vis[tx][ty])
				{
					vis[tx][ty] = 1;
					bfs.push(node(tx, ty, temp.sum + 1));
				}
			}
		}
	}
	cout << ans;
}

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

int h, w, n;
const int MAX_N = 1000;
char map[MAX_N][MAX_N];
struct point{
	int x, y;
	int step;
	point(){
		x = 0; y = 0; step = 0;
	}
	point(int xx, int yy, int ss){
		x = xx;
		y = yy;
		step = ss;
	}
};
struct point p[10];
int dx[4] = { -1, 0, 1, 0 }, dy[4] = { 0, 1, 0, -1 };

int ok(int x, int y){
	if (x >= 0 && x<h && y >= 0 && y<w) return 1;
	return 0;
}

int bfs(int next){
	int nextcheese = next + 1; int res = 0;

	queue<point> q;
	point cur(p[next].x, p[next].y, 0);
	q.push(cur);
	while (q.size()){
		cur = q.front(); q.pop();
		int x = cur.x, y = cur.y;
		int nx, ny;
		for (int i = 0; i<4; i++){
			nx = x + dx[i]; ny = y + dy[i];
			if (ok(nx, ny)){
				if ((map[nx][ny] - '0') == nextcheese) return ++cur.step;
				if (map[nx][ny] == '.'){
					point temp(nx, ny, cur.step + 1);
					q.push(temp);
				}
			}
		}
	}
}

void solve(){
	int sx, sy;
	scanf("%d%d%d", &h, &w, &n);
	for (int i = 0; i<h; i++){
		for (int j = 0; j<w; j++){
			char ch;
			cin >> ch; map[i][j] = ch;
			switch (ch){
			case '.': break;
			case 'X': break;
			case 'S': p[0].x = i; p[0].y = j; break;
			default:
				int t = ch - '0';
				p[t].x = i; p[t].y = j;
			}
		}
	}
	int step = 0;
	for (int i = 0; i<n; i++){
		step += bfs(i);
	}
	printf("%d", step);
}


int main(){
	solve();
}