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 <bits/stdc++.h>
using namespace std;
typedef long long int ll;
const int INF = 1000000000;
#define REP(i,s,n) for(int i=(int)(s);i<(int)(n);i++)
#define rep(i,n) REP(i, 0, n)
typedef pair <int, int> P;
const int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};
char f[1001][1001];
int vd[1001][1001];
int esax[10], esay[10];
int h, w, n;
int bfs(int sx, int sy, int gx, int gy){
    rep(i, h + 1) rep(j, w + 1) vd[i][j] = INF;
    queue <P> opt;
    opt.push(P(sx, sy));
    vd[sx][sy] = 0;
    
    while(opt.size()){
        P p = opt.front(); opt.pop();
        if(p.first == gx && p.second == gy)
          return vd[gx][gy];
        rep(i, 4){
            int nx = p.first + dx[i], ny = p.second + dy[i];
            if(0 <= nx && 0 <= ny && vd[nx][ny] == INF && f[nx][ny] != 'X'){
                opt.push(P(nx, ny));
                vd[nx][ny] = vd[p.first][p.second] + 1;
            }
        }
    }
    //cout << vd[gx][gy] << endl;;
}
int main(){
    cin >> h >> w >> n;
    rep(i, h) rep(j, w){
        cin >> f[i][j];
        if(f[i][j] == 'S')
          esax[0] = i, esay[0] = j;
        if('1' <= f[i][j] && f[i][j] <= '9'){
            int num = f[i][j] - '0';
            esax[num] = i, esay[num] = j;
        }
    }
    rep(j, w) f[h][j] = 'X';
    rep(i, h) f[w][i] = 'X';
    int ans = 0;
    rep(i, n)
      ans += bfs(esax[i], esay[i], esax[i + 1], esay[i + 1]);
    cout << ans << endl;
    return 0;
}

C++: #include <iostream>
#include <vector>
#include <unordered_set>

using namespace std;

int H, W, N;

char nums[1000][1000];

int px, py;

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

int cnt = 0;

void bfs(int a, int b, int index) {
	vector<vector<int> > points{{a, b}};
	int level = 0;
	unordered_set<int> s;
	s.insert(1000 * a + b);
	while (true) {
		level++;
		vector<vector<int> > temp = points;
		points.clear();
		for (vector<int> p: temp) {
			for (int i = 0; i < 4; i++) {
				int tx = dx[i] + p[0];
				int ty = dy[i] + p[1];
				if (tx >= 0 && tx < H && ty >= 0 && ty < W) {
					if (nums[tx][ty] == '0' + index) {
						px = tx;
						py = ty;
						cnt += level;
						//cout << index << endl;
						return;
					}
					if (nums[tx][ty] != 'X' && !s.count(1000 * tx + ty)) {
						s.insert(1000 * tx + ty);
						points.push_back({tx, ty});
					}
				}
			}
		}
	}
}

int main() {
	cin >> H;
	cin >> W;
	cin >> N;
	for (int i = 0; i < H; i++) {
		for (int j = 0; j < W; j++) {
			cin >> nums[i][j];
			if (nums[i][j] == 'S') {
				px = i;
				py = j;
			}
		}
	}
	for (int i = 0; i < N; i++) {
		bfs(px, py, i + 1);
	}
	cout << cnt << endl;
	return 0;
}

C++: #include<stdio.h>
#include<string.h>
#include<queue>
#include<algorithm>
#define MAX_N 1002
using namespace std;
struct node{int x,y;};
char _map[MAX_N][MAX_N];
int dp[MAX_N][MAX_N];
int ox[]={0,0,1,-1};
int oy[]={1,-1,0,0};
int S_x,S_y;
int h,w,cnt;

node make_node(int x,int y){
    node t;
    t.x=x,t.y=y;
    return t;
}
void solve(){
    queue<node> que;
    int step=0;

    for(int i=1;i<=cnt;i++){
        que.push(make_node(S_x,S_y));
        _map[S_x][S_y]='.';
        memset(dp,-1,sizeof(dp));
        dp[S_x][S_y]=step;
        while(!que.empty()){
            node t=que.front();que.pop();
            if(_map[t.x][t.y]=='0'+i){
                step=dp[t.x][t.y];
                S_x=t.x,S_y=t.y;
                break;
            }
            for(int j=0;j<4;j++){
                int x=t.x+ox[j];
                int y=t.y+oy[j];
                if(0<=x&&x<h&&0<=y&&y<w&&_map[x][y]!='X'&&dp[x][y]==-1){
                    que.push(make_node(x,y));
                    dp[x][y]=dp[t.x][t.y]+1;
                }
            }
        }
        while(!que.empty()) que.pop();
    }

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

int main()
{
    while(scanf("%d%d%d",&h,&w,&cnt)!=EOF){
        for(int i=0;i<h;i++)
            scanf("%s",_map[i]);
        for(int j=0;j<h;j++)
            for(int k=0;k<w;k++)
                if(_map[j][k]=='S')
                    S_x=j,S_y=k,j=h,k=w;
        solve();
    }
    return 0;
}

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

using P = pair<int, int>;

constexpr int INF = 1e9;

int bfs(vector<string> const& v, int sy, int sx, int gy, int gx) {
    vector<vector<int>> d(v.size(), vector<int>(v[0].size(), INF));
    queue<P> que;
    que.push(P{sy, sx});
    d[sy][sx] = 0;
    while(!que.empty()) {
        P p = que.front();
        que.pop();
        int dx[4] = {0, 1, 0, -1},
            dy[4] = {1, 0, -1, 0};
        for(int i=0; i<4; ++i) {
            int ny = p.first + dy[i], nx = p.second + dx[i];
            if(ny < 0 || v.size() <= ny || nx < 0 || v[0].size() <= nx || d[ny][nx] != INF) {
                continue;
            }
            if(v[ny][nx] != 'X') {
                d[ny][nx] = d[p.first][p.second] + 1;
                que.push(P{ny, nx});
            }
        }
    }
    return d[gy][gx];
}

int main() {
    int H, W, N;
    cin >> H >> W >> N;
    vector<string> v(H);
    for(int i=0; i<H; ++i) {
        cin >> v[i];
    }
    vector<int> gx(N+1), gy(N+1);
    for(int i=0; i<H; ++i) {
        for(int j=0; j<W; ++j) {
            if(v[i][j] == 'S') {
                gy[0] = i;
                gx[0] = j;
            }
            if(isdigit(v[i][j])) {
                gy[v[i][j]-'0'] = i;
                gx[v[i][j]-'0'] = j;
            }
        }
    }
    int res = 0;
    for(int i=0; i<N; ++i) {
        res += bfs(v, gy[i], gx[i], gy[i+1], gx[i+1]);
    }
    cout << res << endl;
}

C++: #include<iostream>
#include<string>
#include<sstream>
#include<vector>
#include<queue>
using namespace std;
int main()
{
	int H,W,N,sy,sx,gy,gx,out=0;
	queue<int> qx;
	queue<int> qy;
	vector<string> zahyou(H,"");
	cin >> H >> W >> N;
	for(int i=0;i<H;i++)
	{
		cin >> zahyou[i];
	}
	for(int n=0;n<N;n++)
	{	
		for(int i=0;i<H;i++)
		{
			for(int j=0;j<W;j++)
			{
				if(n==0)
				{
					if(zahyou[i][j]=='S') {sy=i;sx=j;}
					if(zahyou[i][j]=='1') {gy=i;gx=j;}
				}
				else
				{	
					if(zahyou[i][j]==n+'0') {sy=i;sx=j;}
					if(zahyou[i][j]==n+'1') {gy=i;gx=j;}
				}
			}
		}
		qx.push(sx);
		qy.push(sy);
		int d[1001][1001]={0};
		bool visited[1001][1001] = {false};
		int dx[4]={-1,0,1,0};
		int dy[4]={0,1,0,-1};
		
		
		while(!qx.empty()&&!qy.empty())
		{
			int x = qx.front();qx.pop();
			int y = qy.front();qy.pop();
			
			for(int k=0;k<4;k++)
			{
				int nx = dx[k];
				int ny = dy[k];

				if(visited[ny][nx]==false&&zahyou[ny][nx]!='X')
				{
					visited[ny][nx]=true;
					d[ny][nx]=d[y][x]+1;
					qx.push(nx);
					qy.push(ny);
				}
			}
		}
		out += d[gy][gx];
	}
	cout << out <<endl;
}