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 <fstream>
#include <vector>
#include <string>
#include <MAP>
#include <queue>
#include <cstdlib>
#include <algorithm>
#include <iterator>
using namespace std;

int H,W,N;
int dx[4]={1,0,-1,0},dy[4]={0,1,0,-1};
char MAP[1000+1][1000+1];
int f[1000+1][1000+1];
int d[1000+1][1000+1];
int main(){
	cin >> H >> W >> N;
	queue<char> qux;
	queue<char> quy;
	vector<int> ans(N+1);
	for(int i=1; i<H+1; ++i){
		for(int j=1; j<W+1; ++j){
			cin >> MAP[i][j];
			f[i][j]=0;
			if(MAP[i][j]=='S'){
				qux.push(i);
				quy.push(j);
				f[i][j]=1;
				d[i][j]=0;
			}
		}
	}
	int x;
	int y;
	for(int i=1; i<N+1; ++i){
		while(1/*qux.size()&&quy.size()*/){
			x=qux.front();
			y=quy.front();
			//cout << x << " " << y << " " << d[x][y] << "\n";
			qux.pop();
			quy.pop();
			//if('0'<=MAP[x][y]&&MAP[x][y]<='9'){
				//if(((int)MAP[x][y]-'0')==i) {
			if(atoi(&MAP[x][y])==i){
					ans[i]=d[x][y];
					for(int j=1; j<H+1; ++j){
						for(int k=1; k<W+1; ++k){
							f[i][j]=0;
						}
					}
					d[x][y]=0;
					break;
				}
			//}
			for(int j=0; j<4; ++j){
				int nx=x+dx[j];
				int ny=y+dy[j];
				if(1<=nx&&nx<=H&&1<=ny&&ny<=W&&MAP[nx][ny]!='X'&&f[nx][ny]==0){
					qux.push(nx);
					quy.push(ny);
					f[nx][ny]=1;
					d[nx][ny]=d[x][y]+1;
				}
			}
		}
	}
	int ANS=0;
	for(int i=1; i<N+1; ++i){
		ANS+=ans[i];
	}
	cout << ANS << "\n";
	return 0;
}

C++: #include "stdio.h"
#include "stdlib.h"
#include "iostream"
#include "math.h"
#include <string.h>
#include <stack>
#include <queue>



using namespace std;
#define fori0(G) for(int i=0;i<G;i++)
#define fori1(G) for(int i=1;i<=G;i++)
#define forj0(G) for(int j=0;j<G;j++)
#define forj1(G) for(int j=1;j<=G;j++)
#define fork0(G) for(int k=0;k<G;k++)
#define fork1(G) for(int k=1;k<=G;k++)
int dx[] = { -1,0,1,0 }, dy[] = { 0,1,0,-1 };
#define nxnycon (0<=nx&&nx<h&&0<=ny&&ny<w) 


//#define inf 10000000
typedef struct { int x;int y; } P;
int h, w, n,co=0;
char ch[1000][1000];
int fl[1000][1000];
P ps[10];


int bfs(int t) {
	int nx, ny;
	//fori0(h)forj0(w) { fl[i][j] = inf; }
	memset(fl, -1, sizeof(fl));
	queue<P> que;
	que.push(ps[t]);
	fl[ps[t].x][ps[t].y] = 0;
	while (que.size()) {
		P p = que.front();
		//printf("(%d,%d)", p.x, p.y);
		que.pop();
		fori0(4){
			nx = p.x + dx[i];
			ny = p.y + dy[i];
			if (nxnycon&&ch[nx][ny] != 'X'&&fl[nx][ny] == -1) {
				fl[nx][ny] = fl[p.x][p.y] + 1;
				if (nx == ps[t + 1].x&&ny == ps[t + 1].y) { return fl[nx][ny]; }
				que.push({ nx,ny });

			}
		}

	}

}

int main() {
	cin >> h >> w >> n;
	fori0(h)forj0(w) {
		cin >> ch[i][j];
		if (ch[i][j] == 'S') { ps[0].x = i;ps[0].y = j; }
		if (('0' < ch[i][j]) && (ch[i][j] <= '9')) {
			ps[(int)(ch[i][j] - '0')].x = i; 
			ps[(int)(ch[i][j] - '0')].y = j;
			
		}
	}
	fori0(n) {
		co+=bfs(i);
	}
	
	printf("%d\n",co);
	//system("pause");
	return 0;
}

C++: #include<cstdio>
#include<queue>
#include<set>
#include<vector>
#include<string>
#include<sstream>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
struct qaq{
    int x,y,step;
    qaq(int a,int b,int c):x(a),y(b),step(c){}
};
char mmp[1005][1005];
bool vis[1005][1005];
int h,w,n,startx,starty,cur,nex[4][2]={0,1,0,-1,1,0,-1,0};
int bfs(int x,int y)
{
    queue<qaq> que;
    vis[x][y]=true;
    que.push(qaq(x,y,0));
    while(!que.empty()){
        qaq q=que.front();
        que.pop();
        for(int i=0;i<4;i++){
            int tx=q.x+nex[i][0];
            int ty=q.y+nex[i][1];
            if(tx<0||tx>=h||ty<0||ty>=w||vis[tx][ty]||mmp[tx][ty]=='X')
                continue;
            if(mmp[tx][ty]=='0'+cur){
                while(!que.empty()) que.pop();
                memset(vis,0,sizeof(vis));
                cur++;
                vis[tx][ty]=true;
                que.push(qaq(tx,ty,q.step+1));
                if(cur==n+1) return q.step+1;
                break;
            }
            vis[tx][ty]=true;
            que.push(qaq(tx,ty,q.step+1));
        }
    }
}
int main()
{
    cur=1;
    scanf("%d%d%d",&h,&w,&n);
    for(int i=0;i<h;i++){
        scanf("%s",mmp[i]);
        for(int j=0;j<w;j++){
            if(mmp[i][j]=='S') startx=i,starty=j;
        }
    }
    printf("%d\n",bfs(startx,starty));
    return 0;
}

C++: #include<stdio.h>
#include<string.h>
#include<algorithm>
#include<queue>

using namespace std;

struct node
{
    int s;
    int x,y;
};

int dir[][2] = {0,1,1,0,0,-1,-1,0};
int vis[1010][1010];
int n,m,k,sx[20],sy[20];

char map[1010][1010];

int bfs(int x,int y,int ex,int ey)
{
    queue<node> q;
    node a,b,d;
    a.x = x;
    a.y = y;
    a.s = 0;
    vis[x][y] = 1;
    q.push(a);
    while(!q.empty())
    {
        b = q.front();
        q.pop();
        if(b.x == ex && b.y == ey)
           {
                return b.s;
           }
        for(int i = 0; i < 4; i++)
        {
            d.x = b.x + dir[i][0];
            d.y = b.y + dir[i][1];
            if(d.x >= 0 && d.x < n && d.y >= 0 && d.y < m && vis[d.x][d.y] == 0)
            {
                if(map[d.x][d.y] >= '1' && map[d.x][d.y] <= '9' || map[d.x][d.y] == '.')
                {
                    vis[d.x][d.y] = 1;
                    d.s = b.s + 1;
                    q.push(d);
                }
            }
        }
    }
}

int main()
{
    while(~scanf("%d%d%d",&n,&m,&k))
    {
        int i,j,t;

        for(i = 0; i < n; i++)
        {
            scanf("%s",map[i]);
            for(j = 0; j < m; j++)
                if(map[i][j] == 'S')
                {
                    sx[0] = i;
                    sy[0] = j;
                }
        }
        for(i = 0; i < n; i++)
            for(j = 0; j < m; j++)
                if(map[i][j] >= '1' && map[i][j] <= '9')
                {
                    sx[map[i][j]-'0'] = i;
                    sy[map[i][j]-'0'] = j;
                }
        int ans = 0;
        for(i = 1; i <= k; i++)
        {
            memset(vis,0,sizeof(vis));
            ans += bfs(sx[i-1],sy[i-1],sx[i],sy[i]);
        }
        printf("%d\n",ans);
    }
    return 0;
}