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 <stdio.h>
#include <queue>

#define MAP_SIZE_MAX 1001
#define INF 100000000

typedef std::pair<int, int> point;

int get_distance(int sx, int sy, int goal,
                 int h, int w, char map[][MAP_SIZE_MAX],
                 int *gx, int *gy) {
  std::queue<point> queue;
  queue.push(point(sx, sy));

  // initalize distance array
  int distance[MAP_SIZE_MAX][MAP_SIZE_MAX];
  for (int i = 0; i < MAP_SIZE_MAX; i++) {
    for (int j = 0; j < MAP_SIZE_MAX; j++) {
      distance[i][j] = INF;
    }
  }
  distance[sx][sy] = 0;

  // ???????????¢?´¢
  while (true) {
    point current = queue.front();
    queue.pop();
    int x = current.first;
    int y = current.second;

    // goal!
    if (map[x][y] == goal + '0') {
      *gx = x;
      *gy = y;
      return distance[x][y];
    }

    // 4 ???????????????
    int d[] = { 0, 1, 0, -1, 0 };
    for (int i = 0; i < 4; i++) {
      int _x = x + d[i];
      int _y = y + d[i + 1];
      if (map[_x][_y] != 'X' &&
          distance[_x][_y] == INF &&
          0 <= _x && _x < h && 0 <= _y && _y < w) {
        distance[_x][_y] = distance[x][y] + 1;
        queue.push(point(_x, _y));
      }
    }
  }
}

int solve(int h, int w, int n, char map[][MAP_SIZE_MAX]) {
  // find start position
  int sx, sy, gx, gy;
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      if (map[i][j] == 'S') {
        sx = i;
        sy = j;
        break;
      }
    }
  }

  int result = 0;
  for (int i = 1; i <= n; i++) {
    result += get_distance(sx, sy, i, h, w, map, &gx, &gy);
  }

  return result;
}

int main() {
  int h, w, n;
  scanf("%d %d %d", &h, &w, &n);

  char map[MAP_SIZE_MAX][MAP_SIZE_MAX];
  for (int i = 0; i < h; i++) {
    scanf("%s", map[i]);
  }

  printf("%d\n", solve(h, w, n, map));

  return 0;
}

C++: #include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#include<cmath>
#include<stack>
#include<queue>
#include<cctype>
#define INF 100000000
using namespace std;

struct  coor
{
	int x, y;
};

char map[1002][1002];
int tim[1002][1002];
int dx[4] = { 0,1,0,-1 };
int dy[4] = { 1,0,-1,0 };
int h, w, n;
coor s;
coor fac[10];
int phy;
int ans;


int bfs(coor fa)
{
	coor next;
	coor now;
	queue<coor>q;
	q.push(s);
	while (!q.empty())
	{
		now = q.front();
		q.pop();
		if (now.x == fa.x&&now.y == fa.y)
		{
			break;
		}
		for (int i = 0;i < 4;i++)
		{
			next.x = now.x + dx[i];
			next.y = now.y + dy[i];
			if (map[next.x][next.y] != 'X'&&next.x >= 0&& next.x < h &&next.y >= 0 && next.y < w && tim[next.x][next.y] ==INF)
			{
				tim[next.x][next.y] = tim[now.x][now.y] + 1;
				q.push(next);
			}
		}
	}
	return tim[fa.x][fa.y];
}

void timeinit(coor st)
{
	for (int i = 0;i < h;i++)
	{
		for (int j = 0;j < w;j++)
		{
			if (map[i][j] != 'X')
				tim[i][j] = INF;
		}
	}
	tim[st.x][st.y] = 0;

}
int main()
{
	while (~scanf("%d%d%d",&h,&w,&n))
	{
		getchar();
		for (int i = 0;i < h;i++)
		{
			for (int j = 0;j < w;j++)
			{
				scanf("%c", &map[i][j]);
				tim[i][j] = INF;
				if (map[i][j] == 'S') { map[i][j] = '.';s.x = i;s.y = j; }
				if (isdigit(map[i][j]))
				{
					fac[map[i][j] - '0'].x = i;
					fac[map[i][j] - '0'].y = j;
				}
			}
			getchar();
		}

		phy = 1;
		tim[s.x][s.y] = 0;
		ans = 0;
		for (int i = 1;i <= n ;i++)
		{
			ans += bfs(fac[i]);
			s.x = fac[i].x;
			s.y = fac[i].y;
			timeinit(s);
		}
		printf("%d\n", ans);
	}
	return 0;
}

C++: #include <iostream>
#include <queue>
#define N 1002
using namespace std;
int bfs(pair<int,int>,pair<int,int>);
int h,w,d[N][N];
string str[N];
int main(){
  int n,i,j,sum;
  pair<int,int> P[10];
  cin >> h >> w >> n;
  for(i=0;i<=w+1;i++) str[0]+='X',str[h+1]+='X';
  for(i=1;i<=h;i++) cin >> str[i],str[i]='X'+str[i]+'X';
  for(i=1;i<=h;i++){
    for(j=1;j<=w;j++){
      if(str[i][j]=='S') P[0].first=i,P[0].second=j;
      if('1'<=str[i][j]&&str[i][j]<='9'){
	P[str[i][j]-'0'].first=i;
	P[str[i][j]-'0'].second=j;
      }
    }
  }
  sum=bfs(P[0],P[1]);
  for(i=1;i<n;i++) sum+=bfs(P[i],P[i+1]);
  cout << sum << endl;
}
int bfs(pair<int,int> s,pair<int,int> g){
  int i,j,ret;
  pair<int,int> t;
  pair<int,int> u;
  queue< pair<int,int> > Q;
  for(i=1;i<=h;i++){
    for(j=1;j<=w;j++){
      d[i][j]=-1;
    }
  }
  Q.push(s);
  d[s.first][s.second]=0;
  while(Q.empty()!=1){
    u=Q.front();
    if(str[u.first][u.second]==str[g.first][g.second]){
      ret=d[u.first][u.second];
      break;
    }
    Q.pop();
    for(i=1;i<=h;i++){
      for(j=1;j<=w;j++){
	if(u.first==i&&u.second==j){
	  if(d[i][j-1]==-1&&str[i][j-1]!='X'){
	    d[i][j-1]=d[u.first][u.second]+1;
	    t.first=i;
	    t.second=j-1;
	    Q.push(t);
	  }
	  if(d[i][j+1]==-1&&str[i][j+1]!='X'){
	    d[i][j+1]=d[u.first][u.second]+1;
	    t.first=i;
	    t.second=j+1;
	    Q.push(t);
	  }
	  if(d[i-1][j]==-1&&str[i-1][j]!='X'){
	    d[i-1][j]=d[u.first][u.second]+1;
	    t.first=i-1;
	    t.second=j;
	    Q.push(t);
	  }
	  if(d[i+1][j]==-1&&str[i+1][j]!='X'){
	    d[i+1][j]=d[u.first][u.second]+1;
	    t.first=i+1;
	    t.second=j;
	    Q.push(t);
	  }
	}
      }
    }
  }
  return ret;
}

C++: #include <algorithm>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <map>
#include <math.h>
#include <set>
#include <stdio.h>
#include <string>
#include <utility>
#include <vector>

using namespace std;

struct N {
  int x, y, cost;
};

bool operator<(const N &lhs, const N &rhs) { return lhs.cost < rhs.cost; }

int main() {
  int h, w, n;
  cin >> h >> w >> n;
  vector<pair<int, int>> gp(n + 1);
  vector<string> mp(h);
  for (int i = 0; i < h; i++) {
    cin >> mp[i];
  }
  for (int i = 0; i < h; i++)
    for (int j = 0; j < w; j++) {
      if (mp[i][j] == 'S') {
        gp[0].first = j;
        gp[0].second = i;
      } else if (mp[i][j] >= '1' && mp[i][j] <= '9') {
        gp[mp[i][j] - '0'].first = j;
        gp[mp[i][j] - '0'].second = i;
      }
    }

  int hx[4] = {0, 0, 1, -1};
  int hy[4] = {1, -1, 0, 0};

  int ans = 0;
  for (int i = 0; i < n; i++) {
    multiset<N> q;
    N start{gp[i].first, gp[i].second, 0};
    q.insert(start);
    vector<vector<bool>> ch(h);
    for (int j = 0; j < h; j++)
      ch[j].resize(w);
    while (q.size() > 0) {
      N now = *q.begin();
      q.erase(q.begin());
      if (ch[now.y][now.x])
        continue;
      ch[now.y][now.x] = true;
      if (now.y == gp[i + 1].second && now.x == gp[i + 1].first) {
        ans += now.cost;
        break;
      }
      for (int j = 0; j < 4; j++) {
        int nx = now.x + hx[j], ny = now.y + hy[j];
        if (nx < 0 || nx >= w || ny < 0 || ny >= h)
          continue;
        if (mp[ny][nx] == 'X')
          continue;
        N next{nx, ny, now.cost + 1};
        q.insert(next);
      }
    }
  }
  cout << ans << endl;
  return 0;
}