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++: //http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0558
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;

int row, col, n;

struct point {
	int x, y;
};

char map[1010][1010];
int d[1010][1010];
int direct[4][2] = { {0,1},{0,-1},{1,0},{-1,0} };

int BFS(int &startX, int &startY, char target) {
	memset(d,0,sizeof(d));

	queue<point> q;
	point p;
	p.x = startX;
	p.y = startY;
	d[startX][startY] = 0;
	q.push(p);
	while (!q.empty()) {
		int nowX = q.front().x,nowY = q.front().y;
		q.pop();

		if (map[nowX][nowY] == target) {
			startX = nowX;
			startY = nowY;
			return d[nowX][nowY];
		}

		int nextX, nextY;
		for (int i = 0; i < 4; i++) {
			nextX = nowX + direct[i][0];
			nextY = nowY + direct[i][1];

			if (nextX >= 0 && nextY >= 0 && nextX < row && nextY < col && 
					map[nextX][nextY] != 'X' && d[nextX][nextY] == 0) {
				d[nextX][nextY] = d[nowX][nowY] + 1;
				p.x = nextX;
				p.y = nextY;
				q.push(p);
			}
		}
	}
	return -1;
}

int main() {
	int startX, startY, sum = 0;

	scanf("%d%d%d", &row, &col, &n);
	for (int i = 0; i < row; i++) {
		scanf("%s", map[i]);
		for (int j = 0; j < col; j++) {
			if (map[i][j] == 'S') {
				startX = i;
				startY = j;
			}
		}
	}

	for (int i = 0; i < n; i++) {
		int dis = BFS(startX, startY, i + '1');
		sum += dis;
	}
	printf("%d\n", sum);
}

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

int H, W, N;
int po[10][2];
int ans = 0;
bool cit[1000][1000];
int tow[1000][1000];
int movx[4] = {0, 1, 0, -1}, movy[4] = {1, 0, -1, 0};

bool isinside(int a, int b){
    return (a >= 0 || b >= 0 || a < H || b < W);
}

int diss(int sx, int sy, int gx, int gy){
    queue<int> que;
    for(int i = 0; i < H; i++){
        for(int j = 0; j < W; j++){
            tow[i][j] = 1000001;
        }
    }
    tow[sx][sy] = 0;
    que.push(sx);
    que.push(sy);
    while(!que.empty()){
        int ax = que.front();
        que.pop();
        int ay = que.front();
        que.pop();
        int ad = tow[ax][ay];
        for(int ii = 0; ii < 4; ii++){
            int i = movx[ii], j = movy[ii];
            if(isinside(ax + i, ay + j) && !(i == 0 && j == 0)){
                if(ax + i == gx && ay + j == gy){
                    return ad + 1;
                }
                if(cit[ax + i][ay + j]){
                    tow[ax + i][ay + j] = min(ad + 1, tow[ax + i][ay + j]);
                    que.push(ax + i);
                    que.push(ay + j);
                }
            }
        }
    }
}

int main(){
    cin >> H >> W >> N;
    for(int i = 0; i < H; i++){
        for(int j = 0; j < W; j++){
            char a;
            cin >> a;
            if(a == '.'){
                cit[i][j] = true;
            }else if(a =='X'){
                cit[i][j] = false;
            }else if(a == 'S'){
                cit[i][j] = true;
                po[0][0] = i;
                po[0][1] = j;
            }else{
                cit[i][j] = true;
                int aa = a - '0';
                po[aa][0] = i;
                po[aa][1] = j;
            }
        }
    }
    for(int i = 0; i < N; i++){
        ans += diss(po[i][0], po[i][1], po[i + 1][0], po[i + 1][1]);
    }
    cout << ans << endl;
    return 0;
}

C++: #include<stdio.h>
#include<queue>
using namespace std;
char sz[1001][1001];
int a,b,c;
struct node{
  int x,y;	
};
typedef struct node Node;
queue<Node>Q;
int bfs(struct node T,int k){
	int cnt=0,flag=1,Flag=1;
	Node vb;
	while(!Q.empty()){
		flag=Flag;
		Flag=0;
	for(int i=0;i<flag;i++){
	for(int dr=-1;dr<=1;dr++){
		for(int dc=-1;dc<=1;dc++){
			if((dc!=0||dr!=0)&&dr*dc==0){
			int xx=Q.front().x+dr;
			int yy=Q.front().y+dc;
			if(xx>=0&&xx<a&&yy>=0&&yy<b){
			if(sz[xx][yy]=='.'||sz[xx][yy]!=k+'0'&&sz[xx][yy]!='X'){
				vb.x =xx;
				vb.y =yy;
				Q.push(vb);
				Flag++;
				sz[xx][yy]=k+'0';
			}
		   if(xx==T.x&&yy==T.y){
		   	while(!Q.empty())Q.pop();
		   	return cnt+1;
		   }
		}
			}
		}
	}
	Q.pop();
}
cnt++;
}
return cnt;
}
int main(){
	
	struct node st[10];
	while(scanf("%d%d%d",&a,&b,&c)){
		getchar();
		for(int i=0;i<a;i++){
			for(int j=0;j<b;j++){
				scanf("%c",&sz[i][j]);
				if(sz[i][j]=='S'){ st[0].x=i;st[0].y=j;sz[i][j]='0';}
				if(sz[i][j]>'0'&&sz[i][j]<='9'){st[sz[i][j]-'0'].x=i;st[sz[i][j]-'0'].y =j;}
			}
			getchar();
		}
		int count=0;
		for(int i=1;i<=c;i++){
			Q.push(st[i-1]);
			count+=bfs(st[i],i-1);
		}
		printf("%d\n",count);
	}
	
}

C++: #include <bits/stdc++.h>

using namespace std;

#define FOR(i,k,n) for(int i = (k); i < (n); i++)
#define REP(i,n) FOR(i,0,n)
#define INF 114514810
#define ELEM(array) (sizeof (array)/sizeof *(array))
#define MAX_N 100
#define SAFE_FREE(ptr) if( ptr != NULL ){ free(ptr); ptr = NULL; }
typedef unsigned int UINT;
typedef long long ll;
typedef queue<pair<int, int>> que;

char city[1005][1005];
int way[1005][1005];
int di[4] = { -1, 0, 0, 1 }; int dj[4] = { 0, -1, 1, 0 };

int main()
{
	int h, w, n;
	cin >> h >> w >> n;
	REP(i, h)REP(j, w)cin >> city[i][j];
	que start;
	REP(i, h)REP(j, w){
		if (city[i][j] == 'S')start.push(make_pair(i, j));
	}
	FOR(k, 1, n + 1)//柔らかい工場順に入れる
	{
		REP(i, h)REP(j, w){
			if (city[i][j]-'0'==k )
			{
				start.push(make_pair(i, j));
			}
		}
	}
	int cnt = 0;

	REP(i, n)
	{
		REP(i, 1005)REP(j, 1005)way[i][j] = INF;
		que q;
		way[start.front().first][start.front().second] = 0;
		q.push(start.front());
		start.pop();
		while (1)
		{
			int tmpi = q.front().first; int tmpj = q.front().second;
			q.pop();
			if (tmpi == start.front().first&&tmpj == start.front().second)
			{
				cnt += way[tmpi][tmpj];
				break;
			}
			else
			{
				REP(i, 4){
					if (tmpi+di[i]>=0&&tmpi+di[i]<h&&tmpj+dj[i]>=0&&tmpj+dj[i]<w&&city[tmpi+di[i]][tmpj+dj[i]]!='X'&&way[tmpi+di[i]][tmpj+ dj[i]] == INF )
					{
						way[tmpi + di[i]][tmpj + dj[i]] = way[tmpi][tmpj] + 1;
						q.push(make_pair(tmpi + di[i], tmpj + dj[i]));
					}
				}
			}
			
		}
	}
	cout << cnt << endl;
	return 0;
}