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 <cstdio>
#include <cstring>
#include <queue>

using namespace std;

typedef pair<int,int> pairi;

int h,w,n;
char map[1002][1002];
int visited[1002][1002];

int x,y;

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

  for(int i=0;i<h+2;i++){
    for(int j=0;j<w+2;j++){
      map[i][j] = 'X';
      if(i == 0 || i == h+1 || j == 0 || j == w+1) continue;
      scanf(" %c", &map[i][j]);
      if(map[i][j] == 'S') x = i, y = j;
    }
  }

  queue<pairi> q;
  pairi c;
      
  char target;

  int r = 0;

  for(int i=0;i<n;i++){
    target = '1'+i;

    q = queue<pairi>();
    memset(visited, 0, sizeof(visited));

    q.push(pairi(x,y));
    visited[x][y] = 1;

    while(!q.empty()){
      c = q.front();
      x = c.first;
      y = c.second;
      q.pop();

      if(map[x][y] == target){
	r += visited[x][y]-1;
	break;
      }

      if(map[x+1][y] != 'X' && visited[x+1][y] == 0){
	q.push(pairi(x+1,y));
	visited[x+1][y] = visited[x][y]+1;
      }

      if(map[x-1][y] != 'X' && visited[x-1][y] == 0){
	q.push(pairi(x-1,y));
	visited[x-1][y] = visited[x][y]+1;
      }

      if(map[x][y+1] != 'X' && visited[x][y+1] == 0){
	q.push(pairi(x,y+1));
	visited[x][y+1] = visited[x][y]+1;
      }

      if(map[x][y-1] != 'X' && visited[x][y-1] == 0){
	q.push(pairi(x,y-1));
	visited[x][y-1] = visited[x][y]+1;
      }
    }
  }

  printf("%d\n", r);
}

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

#define INF 10000000
using namespace std;

int H, W, N;
char M[1000][1000];
int G[10][10];

class Point {
public:
  int x;
  int y;
  int cost;
  Point(int x, int y, int cost = 0) : x(x), y(y), cost(cost) {}
};

void makedist(Point sp) {
  bool visited[1000][1000];
  const int dx[4] = {1,0,-1,0};
  const int dy[4] = {0,1,0,-1};
  queue<Point> que;
  int s;

  if(M[sp.y][sp.x] == 'S') s = 0;
  else               s = M[sp.y][sp.x]-'0';

  fill(visited[0], visited[1000], false);
  visited[sp.y][sp.x] = true;
  que.push(sp);

  while(!que.empty()) {
    Point p = que.front(); que.pop();

    if(M[p.y][p.x] != '.') {
      int g;
      if(M[p.y][p.x] == 'S') g = 0;
      else                   g = M[p.y][p.x]-'0';
      G[s][g] = G[g][s] = p.cost;
    }

    for(int i = 0; i < 4; i++) {
      int nx = p.x + dx[i];
      int ny = p.y + dy[i];
      if(nx < 0 || nx >= W) continue;
      if(ny < 0 || ny >= H) continue;
      if(visited[ny][nx]) continue;
      if(M[ny][nx] == 'X') continue;
      visited[ny][nx] = true;
      que.push(Point(nx, ny, p.cost+1));
    }
  }
}

int make() {
  fill(G[0], G[10], INF);
  for(int i = 0; i < H; i++) {
    for(int j = 0; j < W; j++) {
      if(M[i][j] != '.' && M[i][j] != 'X') {
	makedist(Point(j, i, 0));
      }
    }
  }
}

class State {
public:
  int p;
  int hp;
  int cost;
  bool got[10];

  bool operator <(const State &s) const {
    if(cost != s.cost) return cost > s.cost;
    for(int i = 1; i <= N; i++) {
      if(!got[i] && s.got[i]) return true;
      if(got[i] && !s.got[i]) return false;
    }
    if(hp != s.hp) return hp > s.hp;
    return p < s.p;
  }

  bool get(int i) {
    if(i != 0 && hp >= i && !got[i]) {
      got[i] = true;
      hp++;
      return true;
    } else {
      return false;
    }
  }
};

class State2 {
public:
  int p;
  int hp;
  int got[10];

  State2(State s) {
    p = s.p;
    hp = s.hp;
    for(int i = 1; i <= N; i++) got[i] = s.got[i];
  }

  bool operator <(const State2 &s) const {
    for(int i = 1; i <= N; i++) {
      if(!got[i] && s.got[i]) return true;
      if(got[i] && !s.got[i]) return false;
    }
    if(hp != s.hp) return hp < s.hp;
    return p < s.p;
  }
};

int solve() {
  priority_queue<State> que;
  set<State2> vis;

  State s;

  make();

  s.p = 0;
  s.hp = 1;
  s.cost = 0;
  for(int i = 1; i <= N; i++) s.got[i] = false;

  que.push(s);
  vis.insert(State2(s));

  while(!que.empty()) {
    s = que.top(); que.pop();
    if(s.hp == N+1) return s.cost;

    for(int i = 0; i <= N; i++) {
      if(i == s.p) continue;
      if(G[s.p][i] == INF) continue;
      State ns = s;
      ns.p = i;
      ns.cost += G[s.p][i];
      if(vis.find(State2(ns)) == vis.end()) {
	vis.insert(State2(ns));
	que.push(ns);
      }
      if(ns.get(i)) {
	if(vis.find(State2(ns)) == vis.end()) {
	  vis.insert(State2(ns));
	  que.push(ns);
	}
      }
    }
  }
  return 0;
}
main() {
  cin >> H >> W >> N;
  for(int i = 0; i < H; i++) {
    for(int j = 0; j < W; j++) {
      cin >> M[i][j];
    }
  }
  cout << solve() << endl;
}

C++: #include <cstdio>
#include <iostream>
#include <queue>
#include <map>
#include <string>

using namespace std;

typedef struct P{
    int x;
    int y;
};


int h,w;

const int INF = 100000000;

char feld[101][101];
P ch[11];
int d[101][101];
int dx[4]={1,0,-1,0};
int dy[4]={0,1,0,-1};
int sx,sy;
int gx,gy;
int n;
int ans;

int bfs(){
    for(int i=0;i<n;i++){
        P s_xy=ch[i];
        sx=ch[i].x;
        sy=ch[i].y;
        gx=ch[i+1].x;
        gy=ch[i+1].y;
        for(int y=0;y<h;y++)
            for(int x=0;x<w;x++)
                d[y][x]=INF;
            queue<P> que;
            que.push(s_xy);
            d[sy][sx]=0;
            while(!que.empty()){
                P p=que.front();
                que.pop();
                int x=p.x;
                int y=p.y;
                if(x==gx&&y==gy){
                    ans+=d[gy][gx];
                    break;
                }
                for(int i=0;i<4;i++){
                    int nx=x+dx[i];
                    int ny=y+dy[i];
                    if(nx<0||nx>=w||ny<0||ny>=h)continue;
                    if(feld[ny][nx]!='X'&&d[ny][nx]==INF){
                        P n;
                        n.x=nx;
                        n.y=ny;
                        d[ny][nx]=d[y][x]+1;
                        que.push(n);
                    }
                }
            }
        }
        return 0;
}

int main(){
    cin>>w>>h>>n;
    char c;
    for(int y=0;y<h;y++){
        for(int x=0;x<w;x++){
            scanf(" %c",&feld[y][x]);
            c=feld[y][x];
            if(feld[y][x]=='S'){
                ch[0].x=x;
                ch[0].y=y;

            }
            if(c>='1'&&c<='9'){
                ch[c-'0'].x=x;
                ch[c-'0'].y=y;

            }
        }
    }
    bfs();
    cout<<ans<<endl;
    return 0;
}