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>
#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 << endl;
}

C++: #include <cstdio>
#include <cstring>
#include <utility>
#include <queue>
using namespace std;
typedef pair<int,int> _P;
typedef pair<_P,int> P;
char map[1000][1001];
bool vst[1000][1000];
int dx[]={1,0,-1,0},dy[]={0,1,0,-1};
int H,W,N,X,Y;
int bfs(int target) {
	queue<P> Q;
	Q.push(P(_P(X,Y),0));
	vst[Y][X]=1;
	while(!Q.empty()) {
		P p=Q.front(); Q.pop();
		if(map[p.first.second][p.first.first]==('0'+target)) {
			X=p.first.first,Y=p.first.second;
			return p.second;
		}
		for(int i=0;i<4;i++) {
			int nx=p.first.first+dx[i],ny=p.first.second+dy[i];
			if(0>nx||nx>=W||0>ny||ny>=H) continue;
			if(vst[ny][nx]) continue;
			if(map[ny][nx]=='X') continue;
			Q.push(P(_P(nx,ny),p.second+1));
			vst[ny][nx]=1;
		}
	}
}
int main() {
	scanf("%d %d %d",&H,&W,&N);
	int x,y;
	for(int i=0;i<H;i++) {
		scanf("%s",map[i]);
		for(int j=0;j<W;j++) if(map[i][j]=='S') X=j,Y=i;
	}
	int ans=0;
	for(int i=1;i<=N;i++) {
		ans+=bfs(i);
		memset(vst,0,sizeof(vst));
	}
	printf("%d\n",ans);
}

C++: #include <iostream>
#include <vector>
#include <queue>
#include <algorithm>

#define rep(i,a,b) for(int i=(a);i<(b);i++)
#define pb push_back
#define mp(a,b) make_pair(a,b)
#define all(a) a.begin(),a.end()
#define pii pair<int, int>
#define ll long long
using namespace std; 

#define MAX 10
#define SIZE 1000
#define INF 1<<30

int H, W, N;
char sec[SIZE][SIZE+1];
int tsec[SIZE][SIZE+1];
int move_cnt = INF;
int all_move_cnt = 0;
int facy[10] = {};
int facx[10] = {};
int gy, gx;

struct state {
	int sy, sx, cnt;
	state() {}
	state(int _sy, int _sx, int _cnt) :
		sy(_sy), sx(_sx), cnt(_cnt) {}
};
queue<state> que;

void bfs()
{
	int dy[4] = {-1, 0, 1, 0};
	int dx[4] = {0, 1, 0, -1};
	rep(i,0,SIZE) rep(j,0,SIZE+1) tsec[i][j] = INF;

	while (!que.empty()) {
		state ts = que.front(); que.pop();
		// printf("sy=%d sx=%d cnt=%d\n",ts.sy,ts.sx,ts.cnt);
		if (ts.sy == gy && ts.sx == gx) {
			move_cnt = min(move_cnt, ts.cnt);
			break;
		}

		int ny, nx;
		rep(i, 0, 4) {
			ny = ts.sy + dy[i];
			nx = ts.sx + dx[i];
			if (ny < 0 || ny >= H || nx < 0 || nx >= W) continue;
			if (sec[ny][nx] == 'X' || tsec[ny][nx] != INF) continue;
			state ns(ny, nx, ts.cnt + 1);
			tsec[ny][nx] = ts.cnt+1;
			que.push(ns);
		}
	// rep(i,0,H) { rep(j,0,W) tsec[i][j]>99? printf("99"):printf("%2d",tsec[i][j]); cout << endl;}
	}
}

void solve()
{
	// rep(i,0,N+1) printf("%d y=%d x=%d\n",i,facy[i],facx[i]);

	rep(i,0,N) {
		move_cnt = INF;
		while(!que.empty()) que.pop();
		state s(facy[i], facx[i], 0);
		que.push(s);
		gy = facy[i+1];
		gx = facx[i+1];
		// printf("\n bfs start !! \n");
		bfs();
		all_move_cnt += move_cnt;
	}

	cout << all_move_cnt << endl;
}

void input()
{
	cin >> H >> W >> N;
	rep(i,0,H) { 
		rep(j,0,W) {
			cin >> sec[i][j];
			if (sec[i][j] == 'S') { facy[0] = i; facx[0] = j; }
			if (sec[i][j] >= 49 && 57 >= sec[i][j]) {
				facy[sec[i][j]-48] = i;
				facx[sec[i][j]-48] = j;
			}
		}
	}
	solve();
}

int main(void)
{
	input();
	
	return 0;
}

C++: #include <iostream>
#include <queue>
using namespace std;
typedef pair<int, int> pii;
typedef pair<pii, int> ppi;
int h, w, n;
ppi bfs(char[1005][1005], pii, char);

int solve(char land[1005][1005], pii start, int n) {
  int res = 0;
  char curr = '0';
  for (int i = 0; i < n; ++i) {
    char target = '0' + i + 1;
    ppi tmp_res = bfs(land, start, target);
    start = tmp_res.first;
    res += tmp_res.second;
  }
  return res;
}

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

ppi bfs(char land[1005][1005], pii start, char target) {
  int res = 0;
  int to_time[1005][1005];
  for (int i = 0; i < h; ++i)
    for (int j = 0; j < w; ++j) to_time[i][j] = -1;
  to_time[start.first][start.second] = 0;
  if (land[start.first][start.second] == target) 
    return ppi(start, 0);
  queue<pii> qu;
  qu.push(start);
  while (!qu.empty()) {
    pii tmp = qu.front();
    int tmp_time = to_time[tmp.first][tmp.second];
    qu.pop();
    for (int i = 0; i < 4; ++i) {
      int nx = tmp.first + dx[i], ny = tmp.second + dy[i];
      if (nx >= 0 && nx < h && ny >= 0 && ny < w && land[nx][ny] != 'X' &&
          to_time[nx][ny] == -1) {
        if (land[nx][ny] == target)
          return ppi(pii(nx, ny), tmp_time + 1);
        else {
          to_time[nx][ny] = tmp_time + 1;
          qu.push(pii(nx, ny));
        }
      }
    }  // four directions search
  }
}

int main() {
  char land[1005][1005];
  pii start;
  cin >> h >> w >> n;
  for (int i = 0; i < h; ++i)
    for (int j = 0; j < w; ++j) {
      cin >> land[i][j];
      if (land[i][j] == 'S') start = pii(i, j);
    }
  cout << solve(land, start, n) << endl;
}