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<deque>
#include<algorithm>

using namespace std;

typedef pair<int,int>P;
const int maxn=1e3+5;
const int inf=500;

int h,w,n,sx,sy,Next[4][2]={{0,1},{1,0},{0,-1},{-1,0}},goal[10],book[maxn][maxn];
char s[maxn][maxn];

int judge(int row,int col)
{
    if(row>=0&&row<h&&col>=0&&col<w){
        return 1;
    }
    return 0;
}

int bfs()
{
    int res=0;
    deque<P>q;
    for(int ci=0;ci<n;ci++){
        fill(book[0],book[0]+maxn*maxn,inf);
        q.push_back(P(sx,sy));
        book[sx][sy]=0;
        while(!q.empty()){
            int x=q.front().first;
            int y=q.front().second;
            if((int)s[x][y]==49+ci){
                goal[ci]=book[x][y];
                sx=x;
                sy=y;
                break;
            }
            for(int i=0;i<4;i++){
                int nx=x+Next[i][0];
                int ny=y+Next[i][1];
                if(judge(nx,ny)&&s[nx][ny]!='X'&&book[nx][ny]==inf){
                    q.push_back(P(nx,ny));
                    book[nx][ny]=book[x][y]+1;
                    cout<<nx<<" "<<ny<<endl;
                }
            }
        }
        q.clear();
        res+=goal[ci];
    }
    return res;
}

int main()
{
 //   freopen("F:\\in.txt","r",stdin);
    cin>>h>>w>>h;
    for(int i=0;i<h;i++){
        for(int j=0;j<w;j++){
            cin>>s[i][j];
            if(s[i][j]=='S'){
                sx=i;
                sy=j;
            }
        }
    }
    int res=bfs();
    cout<<res<<endl;
    return 0;
}

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

using namespace std;
int H, W,N;
int flag = 0;  //   ?志是否?束
int flagt = 0;   //   ??一个?点有几个相??点
char SearchMap[1001][1001];
int SearchFlag[1001][1001] = {0};
struct node
{
	int IndexX;
	int IndexY;
	int value;
};

queue<node> q;                                                            

void FoundTheNext(int x,int y,int val)
{                                     
	if (SearchFlag[x][y] < val)
	{
		if (SearchMap[x][y] == 'X')
			return;
		if (SearchMap[x][y] - '0' == val)
		{
			if (val == N)
				flag = 1;
			else
			{
				q.push({ x,y,val + 1 });
				SearchMap[x][y] = '.';
				flagt++;
			}
			
		}
		if (SearchMap[x][y] == '.'|| SearchMap[x][y]-'0'!=val)
		{
			q.push({ x,y,val});
			flagt++;
		}
		return;
	}
	
}

int main()
{
	scanf_s("%d %d %d",&H,&W,&N);
	int starti = 0, startj = 0;  //  ???始的位置

	for (int i = 1; i <= H; i++)
	{
		getchar();
		for (int j = 1; j <= W; j++)
		{
			scanf_s("%c", &(SearchMap[i][j]));
			if (SearchMap[i][j] == 'S')
			{
				starti = i;
				startj = j;
			}
		}
	}

	q.push({starti,startj,1});  //  ?始体力?1
	int resultTime = 0;   //  ??走的?数、??

	int t1 = 1;

	while (!q.empty()&&flag==0)
	{
		
		resultTime++;
		flagt = 0;

		while (t1--&&flag == 0)
		{
			node nodeflag = q.front();

			int x = nodeflag.IndexX, y = nodeflag.IndexY, value = nodeflag.value;

			q.pop();

			SearchFlag[x][y] = value;   //   ?置??数据的?

			if (x > 1)
				FoundTheNext(x - 1, y, value);
			if (x < H)
				FoundTheNext(x + 1, y, value);
			if (y > 1)
				FoundTheNext(x, y - 1, value);
			if (y < W)
				FoundTheNext(x, y + 1, value);
		}
		t1 = flagt;
	}
	if (flag == 1)
		printf_s("%d\n",resultTime);
	system("pause");
	return 1;

}

C++: #include<iostream>
#include<queue>
#include<cstring>
using namespace std;
int n,m,ss;
char a[1001][1001];
int f[10][2];
int d[1001][1001];
int dir[4][2]={0,1,0,-1,1,0,-1,0};
typedef pair<int,int> P;
int bfs(int sx,int sy,int ex,int ey)
{
	memset(d,-1,sizeof(d));
	queue<P> q;
	q.push(P(sx,sy));
	d[sx][sy]=0;
	while(q.size())
	{
		const P p=q.front();
		q.pop();
		if(p.first==ex&&p.second==ey)
		{
			break;
		}
		for(int i=0;i<4;i++)
		{
			int tx=p.first+dir[i][0];
			int ty=p.second+dir[i][1];
			if(tx<0||tx>=n||ty<0||ty>=m||d[tx][ty]!=-1)
			{
				continue;
			}
			if(a[tx][ty]!='X')
			{
				q.push(P(tx,ty));
				d[tx][ty]=d[p.first][p.second]+1;
			}
		}
	}
	return d[ex][ey];
}
int main()
{
	while(cin>>n>>m>>ss)
	{
		for(int i=0;i<n;i++)
		{
			cin>>a[i];
		}
		for(int i=0;i<n;i++)
		{
			for(int j=0;j<m;j++)
			{
				if(a[i][j]=='S')
				{
					f[0][0]=i,f[0][1]=j;
				}
				else if(a[i][j]>='1'&&a[i][j]<='9')
				{
					int x=a[i][j]-'0';
					f[x][0]=i;
					f[x][1]=j;
				}
			}
		}
		int step=0;
		for(int i=0;i<ss;i++)
		{
			step+=bfs(f[i][0],f[i][1],f[i+1][0],f[i+1][1]);
		}
		cout<<step<<endl;
	 } 
}

C++: #include <cstdio>
#include <stdlib.h>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <queue>
#define min(a,b)    (((a) < (b)) ? (a) : (b))
#define max(a,b)    (((a) > (b)) ? (a) : (b))
#define abs(x)    ((x) < 0 ? -(x) : (x))
#define INF 0x3f3f3f3f
#define delta 0.85
#define eps 1e-3
#define PI 3.14159265358979323846
#define MAX_N 1005
using namespace std;
typedef pair<int, int> P;
const int dx[4] = {0, 0, 1, -1};
const int dy[4] = {1, -1, 0, 0};
int H, W, N;
char mp[MAX_N][MAX_N];
int d[MAX_N][MAX_N];

bool judge(int x, int y){
	return x >= 0 && x < H && y >= 0 && y < W && d[x][y] == 0 && mp[x][y] != 'X';
}

int bfs(int &sx, int &sy, char c){
	int fx, fy;
	queue<P> que;
	memset(d, 0, sizeof(d));
	que.push(P(sx, sy));
	while(!que.empty()){
		P p = que.front(); que.pop();
		int x = p.first, y = p.second;
		if(mp[x][y] == c){
			fx = x, fy = y;
			break;
		}
		for(int i = 0; i < 4; i++){
			int nx = x + dx[i], ny = y + dy[i];
			if(judge(nx, ny)){
				d[nx][ny] = d[x][y] + 1;
				que.push(P(nx, ny));
			}
		}
	}
	sx = fx, sy = fy;
	return d[fx][fy];
}

int main(){
	while(~scanf("%d%d%d", &H, &W, &N)){
		int sx, sy;
		for(int i = 0; i < H; i++){
			scanf("%s", mp + i);
			for(int j = 0; j < W; j++){
				if(mp[i][j] == 'S'){
					sx = i, sy = j;
				}
			}
		}
		int res = 0;
		for(int i = 1; i <= N; i++){
			res += bfs(sx, sy, i + '0');
		}
		printf("%d\n", res);
	}
	return 0;
}