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

using namespace std;
struct as
{
    int x,y;
}pos[10];
struct node
{
    int x,y;
    int step;
};
bool vis[1010][1010];
char maze[1050][1050];
int dx[]={0,0,1,-1};
int dy[]={1,-1,0,0};
int H,W,N;

bool check(int x,int y)
{
    if (x<=0 || x>H) return 1;
    if (y<=0 || y>W) return 1;
    if (vis[x][y]) return 1;
    if (maze[x][y] =='X')return 1;
    return 0;
}
int bfs(int m,int n)
{
    memset(vis,0,sizeof vis);
    int sx = pos[m].x, sy = pos[m].y;
    int gx = pos[n].x, gy = pos[n].y;
   // printf("%d %d\n",sx,sy);
   // printf("%d %d\n",gx,gy);
    queue<node> Q;
    node a,next;
    a.step = 0;
    a.x = sx, a.y =sy;
    Q.push(a);
    while(!Q.empty())
    {
        a = Q.front();
        Q.pop();
        if (a.x == gx && a.y == gy)
            return a.step;
        for(int i = 0; i < 4 ;i++)
        {
            int nx = a.x + dx[i];
            int ny = a.y + dy[i];
            if(check(nx,ny))
                continue;
            else
            {
                vis[nx][ny] =1;
                next.x = nx,next.y = ny,next.step = a.step+1;
                Q.push(next);
            }
        }
    }
    return 999999;
}

int main()
{
   // freopen("in.txt","r",stdin);
    while(cin>>H>>W>>N)
    {
        int sx,sy;
        for(int i = 1;i<=H;i++)
        {
            for(int j = 1; j <= W;j++)
            {
                cin>>maze[i][j];
                if (maze[i][j] >='1' && maze[i][j]<='9')
                {
                    pos[maze[i][j]-'0'].x = i;
                    pos[maze[i][j]-'0'].y = j;
                }
                if (maze[i][j]=='S')
                    sx=i,sy = j;
            }
        }

        pos[0].x = sx,pos[0].y = sy;
        int ans = 0;
        for(int i = 0;i<N;i++)
            ans += bfs(i,i+1);
        cout<<ans<<endl;
    }
    return 0;
}

/*
入力例 2
4 5 2
.X..1
....X
.XX.S
.2.X.

出力例 2
12
*/

C++: #include <bits/stdc++.h>
#define rep(i,a,b) for(int i=a ; i<b ; i++)
#define dump(x) cout << #x << " = " << x << endl

using namespace std;

int h, w, n;
char field[1000][1000];
int INF = 999999;

pair<int, int> g[10];

int d[1000][1000];
int dr[4] = {0, -1, 0, 1};
int dc[4] = {-1, 0, 1, 0};

void disp(){
	rep(i,0,h){
		rep(j,0,w) cout << field[i][j];
		cout << endl;
	}
	cout << endl;
	return ;
}

int bfs(pair<int, int> start, pair<int, int> goal ){
	rep(i,0,h) rep(j,0,w) d[i][j] = INF;

	queue<pair<int, int> > que;
	que.push(start);
	d[start.first][start.second] = 0;

	while(!que.empty()){
		pair<int, int> p = que.front();
		que.pop();

		if(p.first == goal.first && p.second == goal.second) break;
		rep(i,0,4){
			int nr = p.first + dr[i];
			int nc = p.second + dc[i];

			if(nr>=0 and nr<h and nc>=0 and nc<w and field[nr][nc]!='X' and d[nr][nc]==INF){
				que.push(pair<int, int> (nr, nc));
				d[nr][nc] = d[p.first][p.second] + 1;
			}
		}
	}

	// cout << d[goal.first][goal.second] << endl;
	return d[goal.first][goal.second];
}

int main(){
	int roop;
	cin >> h >> w >> n;
	rep(i,0,n){
		g[i].first = INF;
		g[i].second = INF;
	}

	rep(i,0,h) rep(j,0,w){
		cin >> field[i][j];
		if(field[i][j] == 'S'){
			g[0].first = i;
			g[0].second = j;
		}

		if('1' <= field[i][j] and field[i][j] <= '9'){
			int temp = field[i][j] - '0';
			roop = max(roop, temp);
			g[temp].first = i;
			g[temp].second = j;
		}
	}

	// disp();
	// rep(i,1,n+1) cout << g[i].first << " " << g[i].second << endl;
	int ans = 0;
	rep(i,0,roop) ans += bfs(g[i], g[i+1]);
	cout << ans << endl;
	return 0;
}

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

#define ll long long
#define INF INT_MAX/3
#define pi 2*acos(0.0)
#define eps 1e-14
typedef pair<int, int> P;
const int MAX_H = 1001;
const int MAX_M = (int)1e+2;
int H, W, N;
char x[MAX_H][MAX_H];
bool used[MAX_H][MAX_H];
int d[MAX_H][MAX_H];

//???????????°
int xp[10], yp[10]; //1???????????????????????????????????¨?????¨???
void input()
{
	cin >> H >> W >> N;
	for (int i = 0; i < H; i++) {
		for (int j = 0; j < W; j++) {
			cin >> x[i][j];
			if (x[i][j] != 'X'&&x[i][j] != 'S' && x[i][j]!='.') {
				int a = atoi(&x[i][j]);
				xp[a] = i, yp[a] = j; 
			}
			if (x[i][j] == 'S') {
				xp[0] = i, yp[0] = j;
			}
		}
	}
}

int dx[] = { -1,0,0,1 }, dy[] = { 0,-1,1,0 };
int x_l, y_l;
int sx, sy, gx, gy;
int bfs() {
	
	queue<P> que;
	for (int i = 0; i < H; i++)
		for (int j = 0; j < W; j++)
			d[i][j] = INF;
	que.push(P(sx, sy));
	d[sx][sy] = 0;

	while (que.size()) {
		P p = que.front(); que.pop();
		if (p.first == gx&&p.second == gy) break;
		for (int i = 0; i < 4; i++) {
			int nx = p.first + dx[i], ny = p.second + dy[i];

			if (0 <= nx&&nx < H && 0 <= ny&&ny < W&&x[nx][ny] != 'X' &&d[nx][ny] == INF) {
				que.push(P(nx, ny));
				d[nx][ny] = d[p.first][p.second] + 1;
			}
		}
	}
	return d[gx][gy];
}
int main() {
	input();
	int ans = 0;
	for (int i = 0; i < N; i++) {
		sx = xp[i], sy = yp[i];
		gx = xp[i + 1], gy = yp[i + 1];
		ans += bfs();
	}

	cout << ans << endl;
	return 0;
}

C++: #include <iostream>
#include <vector>
#include <string>
#include <queue>
#include <tuple>

const std::vector<int> dx{-1, 0, 1, 0}, dy{0, -1, 0, 1};

void solve() {
    int h, w, n;
    std::cin >> h >> w >> n;

    std::vector<std::pair<int, int>> pos(n + 1);
    std::vector<std::string> ss(h);
    for (int i = 0; i < h; ++i) {
        auto& s = ss[i];
        std::cin >> s;

        for (int j = 0; j < w; ++j) {
            auto& c = s[j];

            if (c == 'S') c = '0';
            if (std::isdigit(c)) {
                pos[s[j] - '0'] = std::make_pair(i, j);
                c = '.';
            }
        }
    }

    int ans = 0;
    for (int i = 0; i + 1 <= n; ++i) {
        int sx, sy, gx, gy;
        std::tie(sx, sy) = pos[i];
        std::tie(gx, gy) = pos[i + 1];

        std::vector<std::vector<int>> dist(h, std::vector<int>(w, -1));
        dist[sx][sy] = 0;
        std::queue<std::pair<int, int>> que;
        que.emplace(sx, sy);

        while (!que.empty()) {
            int x, y;
            std::tie(x, y) = que.front();
            que.pop();

            for (int d = 0; d < 4; ++d) {
                int nx = x + dx[d],
                    ny = y + dy[d];

                if (nx < 0 || h <= nx ||
                    ny < 0 || w <= ny ||
                    ss[nx][ny] == 'X' ||
                    dist[nx][ny] != -1) continue;

                dist[nx][ny] = dist[x][y] + 1;
                que.emplace(nx, ny);
            }
        }

        ans += dist[gx][gy];
    }

    std::cout << ans << "\n";
}

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

    solve();

    return 0;
}