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<algorithm>
#include<queue>
#include <iostream>
#define inf 1000000
using namespace std;
int H,W,N,x0,y0;
char map[1005][1005];int d[1005][1005];
int dx[4]={-1,0,1,0};
int dy[4]={0,-1,0,1};int d[1005][1005];
typedef pair<int,int>P;
struct position
{
	int rx,ry,e;
}xy[9];
bool comp(const position a,const position b)
{
	return a.e<b.e;
}
int bfs(int sx,int sy,int gx,int gy)
{
	int tx,ty;
	queue<P>q;

	for(int i=0;i<H;i++)
	{
		for(int j=0;j<W;j++)
		d[i][j]=inf;
	}
	q.push(P(sx,sy));
	d[sx][sy]=0;
	while(!q.empty())
	{
		P p=q.front();
		if(p.first==gx&&p.second==gy)
		return d[p.first][p.second];
		q.pop();
		for(int i=0;i<4;i++)
		{
			tx=p.first+dx[i];
			ty=p.second+dy[i];
			if(tx>=0&&tx<H&&ty>=0&&ty<W&&map[tx][ty]!='X'&&d[tx][ty]==inf)
			{
				d[tx][ty]=d[p.first][p.second]+1;
				q.push(P(tx,ty));
			}
		}
	}
}
int main(void)
{
	while(scanf("%d%d%d",&H,&W,&N)==3)
	{
		int x1[9],y1[9];
		for(int i=0;i<H;i++)
		scanf("%s",&map[i]);
		int t=0;
		for(int i=0;i<H;i++)
		{
			for(int j=0;j<W;j++)
			{
				if(map[i][j]=='S')
				{
					x0=i;
					y0=j;
				}
				if(map[i][j]-'0'>0&&map[i][j]-'0'<=9)
				{
					xy[t].rx=i;
					xy[t].ry=j;
					xy[t].e=map[i][j]-'0';
					t++;
				}
			}
		}

		sort(xy,xy+N,comp);
		int ans=bfs(x0,y0,xy[0].rx,xy[0].ry);
		for(int i=0;i<N-1;i++)
		ans+=bfs(xy[i].rx,xy[i].ry,xy[i+1].rx,xy[i+1].ry);
		printf("%d\n",ans);
	}
	return 0;
}

C++: #include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <string>
#include <functional>
#include <array>
#include <stack>
#include <queue>
#include <chrono>
#include <numeric>

#pragma warning(disable:4996)
#define REP(i,n) for(int i = 0 ; i < n ; ++i)
typedef long long Int;

using namespace std;

struct point{
	Int j, i,step;
	point(Int i_, Int j_,Int s) :i(i_), j(j_),step(s){}
};

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

queue<point> que;
char tile[1000][1000];
int H, W;
bool ed[1000][1000];

point solve(char target)
{
	while (!que.empty()){
		point now(que.front());
		ed[now.j][now.i] = true;
		que.pop();
		REP(i, 4){
			int x = now.j + dx[i];
			int y = now.i + dy[i];

			if (x < 0 || y < 0 || x > W || y > H || ed[x][y])
				continue;

			if (tile[y][x] == target){
				return point(y, x,now.step+1);
			}

			if (tile[y][x] != 'X'){
				que.push(point(y, x, now.step + 1));
				ed[x][y] = true;
			}
		}
	}
}

int main()
{
	cin.tie(0); ios::sync_with_stdio(false);
	fstream fs("input.txt");
	////////////ここから開始///////////
	int n(0);
	cin >> H >> W >> n;

	REP(i, 1000)REP(j, 1000)tile[i][j] = 'X';

	REP(i, H)REP(j, W)fs >> tile[i][j];

	REP(i, H)REP(j, W){ if (tile[i][j] == 'S')que.emplace(i, j, 0); }
	Int ans(0);
	for(int i = 0 ; i < n ; ++i){
		REP(i_1, H)REP(j_1, W){ ed[i_1][j_1] = false; }
		char c = '1' + i;
		point t = solve('1' + i);
		que = {};
		que.emplace(t);
		ans = t.step;
	}
	
	cout << ans << endl;

	return 0;
}

C++: #include <cstdlib>
#include <cstdio>
#include <queue>
#include <climits>
using namespace std;

const int MAX_H = 1000;
const int MAX_W = 1000;
const int MAX_N = 10;

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

typedef struct {
	int x, y;
} node;
node makeNode(int x, int y) {
	node n = {x, y};
	return n;
}

int w, h, n;
// 入力されたフィールド (W * H)
char field[MAX_H][MAX_W];
// 各地点までのステップ数，未到達なら INT_MAX
int step[MAX_H][MAX_W];

int bfs(int startX, int startY, int goalX, int goalY) {
	queue<node> que;
	que.push(makeNode(startX, startY));
	step[startY][startX] = 0;
	while (!que.empty()) {
		node current = que.front();
		que.pop();
		if (current.x == goalX && current.y == goalY) {
			return step[goalY][goalX];
		}
		for (int i = 0; i < 4; i++) {
			int nextX = current.x + dx[i];
			int nextY = current.y + dy[i];
			if (0 <= nextX && nextX < w && 0 <= nextY && nextY < h
					&& field[nextY][nextX] != 'X' && step[nextY][nextX] == INT_MAX) {
				que.push(makeNode(nextX, nextY));
				step[nextY][nextX] = step[current.y][current.x] + 1;
			}
		}
	}
	exit(-1);
	return INT_MAX;
}

int main () {
	scanf("%d %d %d", &h, &w, &n);
	int startX, startY;
	// 入力しながらスタートの座標を探す
	for (int i = 0; i < h; i++) {
		scanf("%s", field[i]);
		for (int j = 0; j < w; j++) {
			if (field[i][j] == 'S') {
				startX = j;
				startY = i;
			}
		}
	}
	
	// 工場を順番に回って合計ステップを計算する
	int ans = 0;
	for (int i = 1; i <= n; i++) {
		// step を INT_MAX で初期化しながらゴールの座標を探す
		int goalX, goalY;
		for (int j = 0; j < h; j++) {
			for (int k = 0; k < w; k++) {
				step[j][k] = INT_MAX;
				if (field[j][k] == '0' + i) {
					goalX = k;
					goalY = j;
				}
			}
		}
		
		
		ans += bfs(startX, startY, goalX, goalY);
		
		startX = goalX;
		startY = goalY;
	}
	
	printf("%d\n", ans);
	return 0;
}

C++: #include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <string>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <algorithm>

using namespace std;

#define rep(i,j) REP((i), 0, (j))
#define REP(i,j,k) for(int i=(j);(i)<(k);++i)
#define BW(a,x,b) ((a)<=(x)&&(x)<=(b))
#define ALL(v) (v).begin(), (v).end()
#define LENGTHOF(x) (sizeof(x) / sizeof(*(x)))
#define AFILL(a, b) fill((int*)a, (int*)(a + LENGTHOF(a)), b)
#define MP make_pair
#define PB push_back
#define F first
#define S second
#define Y first
#define X second
#define INF 1 << 30
#define EPS 1e-10

typedef pair<int, int> pi;
typedef pair<int, pi> pii;
typedef pair<pi, pi> pipi;
typedef vector<int> vi;
typedef queue<int> qi;
typedef long long ll;

int H, W, N;
char field[1000][1000];
int dy[] = {0,1,0,-1}, dx[] = {1,0,-1,0};

int main(){
  scanf("%d%d%d", &H, &W, &N);
  rep(i, H) scanf("%s", field[i]);

  int x, y;
  rep(i, H) rep(j, W) if(field[i][j] == 'S'){ y = i; x = j; break;}
  pii p;
  p = MP(0, MP(y, x));
  REP(i, 1, N+1){
    map<pi, int>m;
    m[MP(p.S.Y, p.S.X)] = 1;
    queue<pii>q;
    q.push(MP(p.F, MP(p.S.Y, p.S.X)));
    while(!q.empty()){
      p = q.front(); q.pop();
      if(field[p.S.Y][p.S.X] == i + '0'){
	if(i == N)  printf("%d\n", p.F);
	break;
      }
      rep(d, 4){
	int ny = p.S.Y + dy[d], nx = p.S.X + dx[d];
	int c = p.F;
	if(ny < 0 || ny >= H || nx < 0 || nx >= W || field[ny][nx] == 'X') continue;
	if(m.count(MP(ny, nx))) continue;
	m[MP(ny, nx)] = 1;
	q.push(MP(c+1, MP(ny, nx)));
      }
    }
  }
  return 0;
}