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

int search(int sx, int sy, int dx, int dy, vector<vector<char> > &f, int w, int h)
{
vector<bool> visit;
queue<pair<pair<int, int>, int> > q;
visit.resize(w * h, false);
q.push(make_pair(make_pair(sx, sy), 0));
while(!q.empty()) {
int x = q.front().first.first;
int y = q.front().first.second;
int cost = q.front().second;
q.pop();
if(visit[x * w + y])
continue;
visit[x * w + y] = true;
if(f[x][y] == 'X')
continue;
if(x == dx && y == dy)
return cost;
int ix[4] = {-1, 0, 0, 1};
int iy[4] = {0, -1, 1, 0};
for(int i = 0; i < 4; ++i) {
int nx = ix[i] + x;
int ny = iy[i] + y;
if(nx < 0 || ny < 0 || nx >= w || ny >= h)
continue;
q.push(make_pair(make_pair(nx, ny), cost + 1));
}
}
return -1;
}

int main() {
int h, w, n;
vector<vector<char> > f;
vector<pair<int, int> > pos;
scanf("%d%d%d", &h, &w, &n);
f.resize(h);
pos.resize(n + 1);
for(int i = 0; i < h; ++i) {
char temp[1024];
scanf("%s", temp);
f[i].resize(w);
for(int j = 0; j < w; ++j) {
f[i][j] = temp[j];
if(f[i][j] == 'S')
pos[0] = make_pair(i, j);
if('0' <= f[i][j] && f[i][j] <= '9')
pos[f[i][j] - '0'] = make_pair(i, j);
}
}
int ans = 0;
for(int i = 1; i <= n; ++i) {
int sx = pos[i - 1].first;
int sy = pos[i - 1].second;
int dx = pos[i].first;
int dy = pos[i].second;
ans += search(sx, sy, dx, dy, f, w, h);
}
printf("%d\n", ans);
return 0;
}

C++: #include<iostream>
#include<utility>
#include<deque>
#include<string>
using namespace std;
const int maxn = 1005;
const int maxN = 12;
const int INF = 100000000;
typedef pair<int, int> P;
char G[maxn][maxn];
int D[maxn][maxn];
P path[maxN];
int H, W, N;
int br, bc;
int gr, gc;
int dr[4] = { -1, 1, 0, 0 }, dc[4] = { 0, 0, -1, 1 };
int bfs()
{
	deque<P> Q;
	for (int i = 0; i < H; i++)
		for (int j = 0; j < W; j++)
		{
			D[i][j] = INF;
		}
	Q.push_back(P(br, bc));
	D[br][bc] = 0;
	while (Q.size())
	{
		P p = Q.front();
		Q.pop_front();
		if (p.first == gr&&p.second == gc)
			break;

		for (int i = 0; i < 4; i++)
		{
			//移?后的位置??nr,nc
			int nr, nc;
			nr = p.first + dr[i];
			nc = p.second + dc[i];
			if (0 <= nr&&nr < H && 0 <= nc&&nc < W&&G[nr][nc] != 'X'&&D[nr][nc]==INF)
			{
				D[nr][nc] = D[p.first][p.second] + 1;
				Q.push_back(P(nr, nc));
			}	
		}
	}
	return D[gr][gc];
}
int main()
{
	//freopen("in.txt", "r", stdin);
	scanf("%d%d%d", &H, &W, &N);
	for (int i = 0; i < H; i++)
	{
		string temp;
		cin >> temp;
		for (int j = 0; j < W; j++)
		{
			G[i][j] = temp[j];
			if (G[i][j] == 'S')
				path[0] = P(i, j);
			if (isdigit(G[i][j]))
				path[G[i][j]-'0'] = P(i, j);
		}
	}
	int sum = 0;
	for (int i = 0; i < N; i++)
	{
		br = path[i].first;
		bc = path[i].second;
		gr = path[i + 1].first;
		gc = path[i + 1].second;
		sum += bfs();
	}
	printf("%d\n", sum);
	return 0;
}

C++: // 2013/11/01 Tazoe

#include <iostream>
#include <queue>
using namespace std;

struct point{
	int y;
	int x;
};

struct state{
	int y;
	int x;
	int t;
};

int main()
{
	int H, W, N;
	cin >> H >> W >> N;

	char F[1002][1002];
	for(int y=0; y<=H+1; y++){
		for(int x=0; x<=W+1; x++){
			F[y][x] = 'X';
		}
	}

	struct point P[10];

	for(int y=1; y<=H; y++){
		for(int x=1; x<=W; x++){
			cin >> F[y][x];

			if(F[y][x]=='S'){
				P[0].y = y;
				P[0].x = x;
				F[y][x] = '.';
			}
			else if('0'<=F[y][x] && F[y][x]<='9'){
				P[F[y][x]-'0'].y = y;
				P[F[y][x]-'0'].x = x;
				F[y][x] = '.';
			}
		}
	}
/*
	for(int y=1; y<=H; y++){
		for(int x=1; x<=W; x++){
			cout << F[y][x];
		}
		cout << endl;
	}
*/
	int sum = 0;

	for(int i=0; i<N; i++){
		struct state s;
		s.y = P[i].y;
		s.x = P[i].x;
		s.t = 0;

		queue<struct state> q;
		q.push(s);

		bool memo[1002][1002];
		for(int y=1; y<=H; y++){
			for(int x=1; x<=W; x++){
				memo[y][x] = false;
			}
		}
		memo[s.y][s.x] = true;

		while(true){
			if(q.empty())
				break;

			s = q.front();

			if(s.y==P[i+1].y && s.x==P[i+1].x){
				sum += s.t;
				break;
			}

			if(F[s.y-1][s.x]=='.' && !memo[s.y-1][s.x]){
				struct state t;
				t.y = s.y-1;
				t.x = s.x;
				t.t = s.t+1;

				q.push(t);
				memo[t.y][t.x] = true;
			}

			if(F[s.y][s.x+1]=='.' && !memo[s.y][s.x+1]){
				struct state t;
				t.y = s.y;
				t.x = s.x+1;
				t.t = s.t+1;

				q.push(t);
				memo[t.y][t.x] = true;
			}

			if(F[s.y+1][s.x]=='.' && !memo[s.y+1][s.x]){
				struct state t;
				t.y = s.y+1;
				t.x = s.x;
				t.t = s.t+1;

				q.push(t);
				memo[t.y][t.x] = true;
			}
			if(F[s.y][s.x-1]=='.' && !memo[s.y][s.x-1]){
				struct state t;
				t.y = s.y;
				t.x = s.x-1;
				t.t = s.t+1;

				q.push(t);
				memo[t.y][t.x] = true;
			}

			q.pop();
		}
	}

	cout << sum << endl;

	return 0;
}

C++: #include <bits/stdc++.h>
using namespace std;

#define rep(i, n) for(int i = 0; i < (n); i++)
template<class T> istream& operator >> (istream& s, vector<T>& v)
{ for (T& x: v) { s >> x; } return s;}

int main()
{
    cin.tie(0); ios::sync_with_stdio(false);

    int H, W, N; cin >> H >> W >> N;
    vector<string> town(H);
    vector<pair<int, int>> path(N+1);
    rep(i, H) {
        cin >> town[i];
        rep(j, W) {
            char c = town[i][j];
            if (c == 'S') {
                path[0] = make_pair(i, j);
            } else if ('1' <= c && c <= '9') {
                path[c-'0'] = make_pair(i, j);
            }
        }
    }

    int ans = 0;

    int dw[4] = { 0, 0,-1, 1 };
    int dh[4] = {-1, 1, 0, 0 };

    rep(i, N) {
        pair<int, int>& s = path[i];    // start
        pair<int, int>& e = path[i+1];  // end
    
        vector<vector<int>> d(H, vector<int>(W, -1));
        queue<pair<int, int>> q;
    
        d[s.first][s.second] = 0;
        q.push(make_pair(s.first, s.second));
        
        while (!q.empty()) {
            pair<int, int> hw = q.front(); q.pop();
            rep(j, 4) {
                int h = hw.first + dh[j];
                int w = hw.second + dw[j];
                if (0 <= h && h < H && 0 <= w && w < W && town[h][w] != 'X' && d[h][w] == -1) {
                    d[h][w] = d[hw.first][hw.second]+1;
                    if (h == e.first && w == e.second) {
                        while (!q.empty()) q.pop();
                        break;
                    }
                    q.push(make_pair(h, w));
                }
            }
        }
        ans += d[e.first][e.second];
    }
    
    cout << ans << endl;
}