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 <cstdio>
#include <queue>
using namespace std;

int h,w,n;
int en;//energy indicates which cheese to eat next
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\n", step);
}


int main(){
    solve();
}

C++: #include <fstream>
#include <iostream>
#include <queue>
using namespace std;
const int MAX = 1000;
const int INF = 10000000;
typedef pair<int, int> P;
int h,w,n;
// 移動の4方向
int dx[4] = {1, -1, 0, 0};
int dy[4] = {0, 0, 1, -1};
// チーズ工場のマップ
short field[MAX][MAX];
// スタートから各点への最短距離
int d[MAX][MAX];
// 幅優先探索の関数の返り値用
typedef struct {
  int x;
  int y;
  int cnt;
} Cheeze;

// 地点(sx,sy)から目標地点（工場i）までの最短距離を求める幅優先探索
Cheeze bfs(int sx, int sy, char i) {
  // スタート地点は距離0
  d[sy][sx] = 0;
  queue<P> qu;
  qu.push(P(sx, sy));

  // 工場iに達するまで繰り返す
  while (true) {
    P p = qu.front();
    qu.pop();
    // ゴールなら終了
    if (field[p.second][p.first] == i) {
      Cheeze res = {p.first, p.second, d[p.second][p.first]};
      return res;
    }
    // 4方向
    for (int j = 0; j < 4; j++) {
      int nx = p.first + dx[j];
      int ny = p.second + dy[j];
      // 移動可能判定など
      if (nx >= 0 && nx < w && ny >= 0 && ny < h &&
          d[ny][nx] == INF && field[ny][nx] != -1) {
        qu.push(P(nx,ny));
        d[ny][nx] = d[p.second][p.first] + 1;
      }
    }
  }
}

int main() {
  // 入力
  int sx, sy;
  int cnt = 0;
  Cheeze cheeze;
  // ifstream ifs( "test.txt" );
  cin >> h >> w >> n;
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      char cel;
      cin >> cel;
      if (cel == 'X') {
        field[i][j] = -1;
      } else if (cel == '.') {
        field[i][j] = 0;
      } else if (cel == 'S') {
        field[i][j] = 0;
        sx = j;
        sy = i;
      } else {
        field[i][j] = (short)(cel - '0');
      }
    }
  }

  // 計算
  for (int i = 1; i <= n; i++) {
    // 最短距離dの初期化
    for (int j = 0; j < MAX; j++) {
      for (int k = 0; k < MAX; k++) {
        d[j][k] = INF;
      }
    }
    cheeze = bfs(sx, sy, i);
    // スタート地点を更新
    sx = cheeze.x;
    sy = cheeze.y;
    cnt += cheeze.cnt;
  }

  // 出力
  cout << cnt << endl;
}

C++: #include<cstdio>
#include<queue>
using namespace std;
typedef pair<int, int> P;

int w, h, n;
char s[1000][1001];
int d[1000][1000];
int dx[4] = {0, 1, 0, -1};
int dy[4] = {1, 0, -1, 0};

int main() {
  scanf("%d%d%d", &h, &w, &n);
  for (int i = 0; i < h; i++) scanf("%s", s[i]);
  int sx, sy;
  for (int i = 0; i < h; i++) for (int j = 0; j < w; j++) if (s[i][j] == 'S') sy = i, sx = j;
  int ans = 0;
  for (int i = 0; i < n; i++) {
    char g = '1' + (char)i;
    queue<P> que;
    for (int i = 0; i < h; i++) for (int j = 0; j < w; j++) d[i][j] = -1;
    d[sy][sx] = 0;
    que.push(P(sy, sx));
    bool end = false;
    while (!que.empty()) {
      P p = que.front(); que.pop();
      for (int i = 0; i < 4; i++) {
        int y = dy[i] + p.first, x = dx[i] + p.second;
        if (x < 0 || y < 0 || x == w || y == h) continue;
        if (s[y][x] == 'X' || d[y][x] != -1) continue;
        if (s[y][x] == g) {
          ans += d[p.first][p.second] + 1;
          sy = y, sx = x;
          end = true;
        }
        d[y][x] = d[p.first][p.second] + 1;
        que.push(P(y, x));
      }
      if (end) break;
    }
  }
  printf("%d\n", ans);
}

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

const int INF = 1<<30;
const int maxn = 1000+10;

int w,h,n;
char mp[maxn][maxn];
int d[maxn][maxn];

int dir[4][2] = {
	{-1,0},
	{1,0},
	{0,1},
	{0,-1},
};

int fac[10][2];

int bfs(int sx,int sy,int gx,int gy){
	memset(d,-1,sizeof(d));

	queue<pair<int,int> > Q;
	Q.push(make_pair(sx,sy));
	d[sx][sy] = 0;
	while(!Q.empty()){
		pair<int,int> p = Q.front(); Q.pop();
		if(p.first==gx && p.second==gy) break;

		for(int i=0; i<4; i++){
			int tx = p.first + dir[i][0];
			int ty = p.second + dir[i][1];
			if(tx>=0 && tx<h && ty>=0 && ty<w && mp[tx][ty]!='X' && d[tx][ty]==-1){
				Q.push(make_pair(tx,ty));
				d[tx][ty] = d[p.first][p.second] + 1;
			}
		}
	}

	return d[gx][gy];
}

int main(){
	scanf("%d%d%d",&h,&w,&n);	
	for(int i=0; i<h; i++)
		for(int j=0; j<w; j++)
			cin >> mp[i][j];

	for(int i=0; i<h; i++){
		for(int j=0; j<w; j++){
			if(mp[i][j] == 'S'){
				fac[0][0] = i;
				fac[0][1] = j;
				mp[i][j] = '.';
			}else if(isdigit(mp[i][j])){
				int index = mp[i][j] - '0';
				fac[index][0] = i;
				fac[index][1] = j;
			}
		}
	}

	int step = 0;
	for(int i=0; i<n; i++){
		step += bfs(fac[i][0],fac[i][1],fac[i+1][0],fac[i+1][1]);
	}

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