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<queue>

using namespace std;

const int INF = 1000000;
const int MAX_N = 1003;
const int MAX_M = 1003;
char map[MAX_N][MAX_M];
int n, m, k, dis[MAX_N][MAX_M];
int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};

struct state {
    int x, y;
} p[11];

int bfs(int sx, int sy, int gx, int gy) {
    for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++)
            dis[i][j] = INF;
    queue<state>que;
    state start;
    start.x = sx, start.y = sy;
    dis[start.x][start.y] = 0;
    que.push(start);
    while (que.size()) {
        state cur = que.front();
        que.pop();
        if (cur.x == gx && cur.y == gy)return dis[cur.x][cur.y];
        for (int i = 0; i < 4; i++) {
            int nx = cur.x + dx[i], ny = cur.y + dy[i];
            if (dis[nx][ny] == INF && map[nx][ny] != 'X') {
                dis[nx][ny] = dis[cur.x][cur.y] + 1;
                state news;
                news.x = nx, news.y = ny;
                que.push(news);
            }
        }
    }
    return -1;
}

void solve() {

    int ans = 0;
    for (int i = 0; i <= k - 1; i++) {
        ans += bfs(p[i].x, p[i].y, p[i + 1].x, p[i + 1].y);
    }
    printf("%d\n", ans);
}

int main() {
    scanf("%d%d%d", &n, &m, &k);
    for (int i = 0; i < n; i++)
        scanf("%s", map[i]);
    for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++) {
            if (map[i][j] == 'S')
                p[0].x = i, p[0].y = j;
            if (map[i][j] != 'X' && map[i][j] != 'S') {
                int id = map[i][j] - '0';
                p[id].x = i;
                p[id].y = j;
            }
        }
    solve();
    return 0;
}

C++: /*
*
*/
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<string>
#include<queue>
#define CLR(ARR,NUM) memset(ARR,NUM,sizeof(ARR))
#define GETNUM(NUM) scanf("%d",&NUM)
#define faster_io() ios_base::sync_with_stdio(false)
using namespace std;
const int MAXN = 1010;
char map[MAXN][MAXN];
bool vis[10][MAXN][MAXN];
struct node{
	int x;
	int y;
	int deep;
	int n;
};
int dx[]={0,0,1,-1};
int dy[]={1,-1,0,0};

int main()
{
	CLR(vis,false);
	CLR(map,'X');
	int h,w,n;
	cin >> h >> w >> n;
	getchar();
	int sx,sy;
	for(int i=1;i<=h;i++){
		for(int j=1;j<=w;j++){
			map[i][j]=getchar();
			if(map[i][j]=='S'){
				sx=i;
				sy=j;
			}
		}
		getchar();
	}
	node t;
	t.x=sx;
	t.y=sy;
	t.deep=0;
	t.n=0;
	queue<node>q;
	vis[0][sx][sy]=true;
	q.push(t);
	int ans = -1;
	while(!q.empty()){
		node cur=q.front();
		if(cur.n==n){
			ans=cur.deep;
			break;
		}
		q.pop();
		for(int i=0;i<4;i++){
			int tx=cur.x+dx[i];
			int ty=cur.y+dy[i];
			if(map[tx][ty]!='X'&&!vis[cur.n][tx][ty]){
				node t = cur;
				t.x=tx;
				t.y=ty;
				t.deep++;
				if(map[tx][ty]=='1'+t.n){
					t.n++;
				}
				vis[t.n][tx][ty]=true;
				q.push(t);
			}
		}
	}
	cout << ans << endl;
	return 0;
}

C++: #include <bits/stdc++.h>
using namespace std;
const int inf=1<<30;
int dp[9][1000][1000];
int mx[]={1,0,-1,0},my[]={0,1,0,-1};
int main(){
	int h,w,n;	cin>>h>>w>>n;
	vector<string> s(h);
	int sx,sy;
	for(int i=0;i<h;i++){
		cin>>s[i];
		for(int j=0;j<w;j++){
			if(s[i][j]=='S'){
				sx=j,sy=i;
				break;
			}
		}
	}
	for(int i=0;i<9;i++){
		for(int j=0;j<1000;j++){
			for(int k=0;k<1000;k++)	dp[i][j][k]=inf;
		}
	}
	queue<pair<int,int>> q;
	int ans=0;
	for(int i=0;i<n;i++){
		dp[i][sy][sx]=0;
		q.push(make_pair(sy,sx));
		while(!q.empty()){
			auto now=q.front();	q.pop();
			int y=now.first,x=now.second;
			for(int j=0;j<4;j++){
				int nx=x+mx[j],ny=y+my[j];
				if(nx<0||w<=nx||ny<0||h<=ny)	continue;
				if(s[ny][nx]=='X')	continue;
				if(s[ny][nx]-'0'==i+1){
					sy=ny;	sx=nx;
					ans+=dp[i][y][x]+1;
					while(!q.empty())	q.pop();
					break;
				}
				if(dp[i][ny][nx]==inf){
					dp[i][ny][nx]=dp[i][y][x]+1;
					q.push(make_pair(ny,nx));
				}
			}
		}
	}
	cout<<ans<<endl;
	return 0;
}

C++: #include <iostream>
#include <queue>
#include <map>

using namespace std;

typedef pair<int, int> P;

void init_minutes(int h, int w, int minutes[1000][1000]) {
    for (int y=0; y<h; y++) {
        for (int x=0; x<w; x++) {
            minutes[x][y] = -1;
        }
    }
}

int main() {
    int h, w, n;
    int dx[] = {0, 1, 0, -1};
    int dy[] = {1, 0, -1, 0};
    int minutes[1000][1000];
    char area[1000][1000];
    P start;

    cin >> h >> w >> n;
    for (int y=0; y<h; y++) {
        for (int x=0; x<w; x++) {
            cin >> area[x][y];
            if (area[x][y] == 'S') {
                start.first = x;
                start.second = y;
            }
        }
        cin.ignore();
    }
    minutes[start.first][start.second] = 0;
    for (int m=1; m<=9; m++) {
        queue<P> q;
        q.push(start);
        int min = minutes[start.first][start.second];
        init_minutes(h, w, minutes);
        minutes[start.first][start.second] = min;
        while (q.size() > 0) {
            int x = q.front().first;
            int y = q.front().second;
            q.pop();
            for (int i=0; i<4; i++) {
                int nx = x+dx[i];
                int ny = y+dy[i];
                if (nx < 0 || w <= nx || ny < 0 || h <= ny) {
                    continue;
                }
                if (minutes[nx][ny] >= 0 || area[nx][ny] == 'X') {
                    continue;
                }
                minutes[nx][ny] = minutes[x][y]+1;
                if (area[nx][ny] == '0'+m) {
                    start.first = nx;
                    start.second = ny;
                    break;
                }
                q.push(P(nx, ny));
            }
        }
    }
    cout << minutes[start.first][start.second] << endl;
    return 0;
}