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

#define INF (1e+9)
#define LLINF (1e+18)
#define LL long long

using namespace std;

typedef struct info{
	int nx;
	int ny;
	int cost;
	int target;
	info(int a,int b,int c,int d){
		nx = a;
		ny = b;
		cost = c;
		target = d;
	}
}info;

bool isNumChar(char c){
	if((0 <= c-48)&&(c-48 <= 9))return true;
	return false;
}

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

int W,H;
int N;

int sx[16] = {0};
int sy[16] = {0};

char field[1024][1024] = {""};
int record[1024][1024][10] = {0};
bool flag[16] = {false};

queue<info> que;


int ans;



int recordReset(){
	for(int i = 0;i < 1024;i++){
		for(int j = 0;j < 1024;j++){
			for(int k = 0;k < 16;k++){
				record[i][j][k] = INF;
			}
		}
	}
}

int bfs(){
	info now(0,0,0,0);
	info next(0,0,0,0);
	for(int i = 0;i < N;i++){
		next = info(sx[i],sy[i],0,i+1);
		que.push(next);
	}

	recordReset();
	while(!que.empty()){
		now = que.front();
		que.pop();
		if(!flag[now.target]){
			//printf("###(%d,%d):::cost<%d>:::target<%d>\n",now.nx,now.ny,now.cost,now.target);
			if(record[now.nx][now.ny][now.target] > now.cost){
				record[now.nx][now.ny][now.target] = now.cost;
				if((sx[now.target] == now.nx)&&(sy[now.target] == now.ny)){
					flag[now.target] = true;
					//printf("###target<%d> completed\n",now.target);
					ans += record[now.nx][now.ny][now.target];
				}
				else{
					switch(field[now.nx][now.ny]){
					case 'X':
						break;
					default:
						for(int i = 0;i < 4;i++){
							next = info(now.nx + dx[i],now.ny + dy[i],now.cost + 1,now.target);
							que.push(next);
						}
						break;
					}
				}
			}
			else{

			}
		}
	}
}


int main (void){
	//while(true){
		scanf("%d%d",&H,&W);
		scanf("%d",&N);
		//if((W == 0)&&(H == 0))break;

		ans = 0;

		//Reset Field
		for(int i = 0;i < 1024;i++){
			for(int j = 0;j < 1024;j++){
				field[j][i] = 'X';
			}
		}

		//Reset Flag
		for(int i = 0;i < 16;i++){
			flag[i] = false;
		}

		//Reading Data
		for(int i = 1;i <= H;i++){
			scanf(" ");
			for(int j = 1;j <= W;j++){
				scanf("%c",&field[j][i]);
				if(isNumChar(field[j][i])){
					sx[field[j][i]-48] = j;
					sy[field[j][i]-48] = i;
					//printf("###<%d>(%d,%d)\n",field[j][i] - 48,sx[field[j][i] - 48],sy[field[j][i] - 48]);

				}
				else if(field[j][i] == 'S'){
					sx[0] = j;
					sy[0] = i;
					//printf("###<S>(%d,%d)\n",j,i);
				}
			}
		}

		//DBG
		/*for(int i = 0;i < N;i++){
			printf("<%d>(%d,%d)\n",i,sx[i],sy[i]);
		}*/

		bfs();

		printf("%d\n",ans);
	//}

	return 0;
}

C++: #include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
int h, w, n, s;
char g[1001][1001];
bool v[1001][1001];
int id[8] = {0, -1, 0, 1, -1, 0, 1, 0};
int main() {
    scanf("%d %d %d", &h, &w, &n);
    for (int i = 0; i < h; ++i) {
        getchar();
        for (int j = 0; j < w; ++j) {
            while (~scanf("%c", &g[i][j]) && g[i][j] == ' ');
            //printf("%c",g[i][j]);
            if (g[i][j] == 'S') s = i * w + j;
        }
    }
    int ans = 0;
    char c = '0';
    while (c != n + '0') {
        c += 1;
        queue<pair<int, int> > q;
        memset(v, 0, sizeof v);
        v[s / w][s % w] = true;
        q.push({s, 0});
        while (!q.empty()) {
            int i = q.front().first / w, j = q.front().first % w, step = q.front().second;
            //printf("123%d\n%c\n", step, g[i][j]);
            if (g[i][j] == c) {
                s = i * w + j;
                ans += step;
                //printf("%d %d %d\n", i, j, ans);
                break;
            }
            q.pop();
            for (int k = 0; k < 8; k += 2) {
                int ni = i + id[k], nj = j + id[k + 1];
                if (ni >= 0 && ni < h && nj >= 0 && nj < w && !v[ni][nj] && g[ni][nj] != 'X') {
                    v[ni][nj] = true;
                    q.push({ni * w + nj, step + 1});
                }
            }
        }
    }
    printf("%d\n", ans);
    return 0;
}

C++: #include<bits/stdc++.h>
#define x first
#define y second
#define u(i,a,b) for(int i=a;i<b;i++)
using namespace std;
pair<int,int> p[12];
bool t[1010][1010],v[1010][1010];
queue<pair<int,pair<int,int> > >Q;
int main(){
	int h,w,k,a=0,dx[]={0,1,0,-1},dy[]={1,0,-1,0};cin>>h>>w>>k;
	u(i,0,h)u(j,0,w){t[i][j]=1;char z;cin>>z;
		if(z=='X')t[i][j]=0;if(z=='S')p[0]=make_pair(i,j);
		if(z>'0'&&z<='9')p[z-'0']=make_pair(i,j);
	}
	u(r,0,k){Q.push(make_pair(0,p[r]));u(i,0,h)u(j,0,w)v[i][j]=0;v[p[r].x][p[r].y]=1;
		while(1){int L=Q.front().x,Y=Q.front().y.x,X=Q.front().y.y;
			if(Y==p[r+1].x&&X==p[r+1].y){a+=L;break;}
			u(i,0,4){int f=Y+dy[i],g=X+dx[i];if(f+1&&f<h&&g+1&&g<w){
				if(t[f][g]==1&&v[f][g]==0){v[f][g]=1;Q.push(make_pair(L+1,make_pair(f,g)));}
			}}Q.pop();
		}while(!Q.empty())Q.pop();
	}cout<<a<<endl;return 0;
}

C++: #include<iostream>
#include<algorithm>
#include<stdio.h>
#include<queue>
using namespace std;
queue<pair<int, int>>q;
pair <int, int>p;
pair <int, int> po;
int n, m,c;
char ma[101][101];
int ix, iy,x,y;
int te[101][101];
int xw[4] = { 1, 0, -1, 0 };
int yw[4] = { 0, 1, 0, -1 };
char name[10] = { '1', '2', '3', '4', '5', '6', '7', '8', '9' };
int nat = 0;
int na;
int op = 10000;
int main()
{
	cin >> n >> m>>na;
	for (int i = 0; i < n; i++){
		for (int i2 = 0; i2 < m; i2++){
			cin >> ma[i][i2];
			te[i][i2] = op;
			if (ma[i][i2] == 'S'){
				p.first = i;
				p.second = i2;
			}
		}
	}
	
	int count;

	count = 0;
	q.push(p);
	
	te[p.first][p.second] = 0;
	while (!q.empty()){
		p = q.front();
		po = p;
		q.pop();
		
		for (int i = 0; i < 4; i++){
			x = p.first + xw[i];
			y = p.second + yw[i];
			if (0<=x && x<=n&&0<=y && y<=m&&ma[x][y] != 'X'&&te[x][y] == op){

				if (ma[x][y] == name[nat]){
					po.first = x;
					po.second = y;
					while (!q.empty()){ q.pop(); }
					q.push(po);
					po = p;
					count += te[p.first][p.second] + 1;
					nat++; 
					if (nat == na){ cout << count << endl; return 0; }
					//memset(te, op, sizeof(te));
					for (int i2 = 0; i2 <= n; i2++){
						for (int i3 = 0; i3 <= m; i3++){
							te[i2][i3] = op;
						}
					}
					te[x][y] = 0;
					break;
				}

				else{
					po.first = x;
					po.second = y;
					q.push(po);
					po = p;
					te[x][y] = te[p.first][p.second] + 1;
				}
			}
		}
	}
}