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 <stdio.h>
#include <cstring>
#include <queue>
using namespace std;

char ma[1005][1005];int vis[1005][1005];
int w,h,n;

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

struct node
{
    int x,y,time;

};
node start;

void bfs(node st,char ed)
{
    queue<node> que;
    que.push(st);
    vis[st.x][st.y]=1;
    while(!que.empty())
    {
        node no=que.front();
        que.pop();
        for(int i=0;i<4;i++)
        {
            int x=no.x+dx[i];
            int y=no.y+dy[i];
            if(vis[x][y]||x>=w||x<0||y>=h||y<0||ma[x][y]=='X')
                continue;
            if(ma[x][y]==ed)
            {
                start.x=x;
                start.y=y;
                start.time=no.time+1;
                return ;
            }
            vis[x][y]=1;
            node no1;
            no1.x=x;no1.y=y;no1.time=no.time+1;
            que.push(no1);
        }
    }
}

int main()
{
    while(~scanf("%d %d %d", & w, & h, & n))
    {
        for(int i=0;i<w;i++)
        {
            scanf("%s",&ma[i]);
            for(int j=0;j<h;j++)
                if(ma[i][j]=='S')
                {
                    start.x=i;
                    start.y=j;
                    start.time=0;
                }

        }
            for(int i=0;i<n;i++)
            {
                memset(vis,0,sizeof(vis));
                bfs(start,i+'1');
            }

            printf("%d\n",start.time);


    }
}

C++: #include<iostream>
#include<queue>
#include<cstring>
using namespace std;
int h,w,n;
char m[1001][1001];
int dx[4]={0,0,-1,1};//四个方向;
int dy[4]={-1,1,0,0};
bool bj[1001][1001];
int start_x;
int start_y;
int total;
int cnt;
struct Node{
    int x,y;
    int time;
};
bool pd(int a,int b)  //判断是否在矩?范?内;
{
    if(a>=0&&a<h&&b>=0&&b<w)
        return true;
    return false;
}
void BFS(int a)
{
    memset(bj,false,sizeof(bj));
    int i;
    Node start;
   // char nl='0'+a;//?个?酪厂;
    start.x=start_x;
    start.y=start_y;
    start.time=0;
    cnt=0;
    bj[start.x][start.y]=true;
    queue<Node> Q;
    Q.push(start);//起点入?

    while(!Q.empty())
    {
       Node q1;
       q1=Q.front();
       Q.pop();
       if((int)(m[q1.x][q1.y]-'0')==a)
        {
            total+=q1.time;
            start_x=q1.x;
            start_y=q1.y;
            //cout<<q1.time<<endl;
           return ;
        }
       for(i=0;i<4;i++)
       {
           Node q2;
           q2.x=q1.x+dx[i];
           q2.y=q1.y+dy[i];
           if(pd(q2.x,q2.y))
           {
               if(m[q2.x][q2.y]!='X'&&!bj[q2.x][q2.y])
               {
                      //q2.time++;
                       //total++;
                       q2.time=q1.time+1;
                      // cout<<q2.time<<endl;
                    if(!bj[q2.x][q2.y]){

                       bj[q2.x][q2.y]=true;
                        Q.push(q2);
                    }
                }
           }
       }
    }

}
int main()
{

       cin>>h>>w>>n;

        int i,j;
        for(i=0;i<h;i++)
        {
            for(j=0;j<w;j++)
            {
                cin>>m[i][j];
                if(m[i][j]=='S')
                {
                    start_x=i;
                    start_y=j;
                   // start.time=0;
                }
            }
        }
        total=0;
        for(i=1;i<=n;i++)
            BFS(i);
        cout<<total<<endl;
    return 0;
}

C++: #include <iostream>
#include <cstdio>
#include <cstdlib>
#include <time.h>
#include <math.h>
#include <vector>
#include <queue>
#include <map>
#include <set>
#include <algorithm>
#include <iterator>
#include <sstream>
#include <string>
#include <bitset>
using namespace std;
#define rep(I,N) for(int I = 0; I < (int)(N); I++)
#define FIN(V) cout<<V<<endl
#define pb push_back
#define INF (1 << 30)
typedef pair<int, int> P;
typedef long long ll;
typedef priority_queue<int> pq;
int StrToInt(string);
string IntToStr(int);
struct Data{
	int hp, x, y, cost;
	Data(int _hp, int _x, int _y, int _cost){
		hp = _hp;
		x = _x;
		y = _y;
		cost = _cost;
	}
	Data(){}
};
int dx[4] = {1, -1, 0, 0};
int dy[4] = {0, 0, 1, -1};

int w, h, n, sx, sy;
int gx[11], gy[11];
int memo[11][1001][1001];
string maze[1001];

int main(void){
	fill_n(**memo, 11*1001*1001, INF);
	cin >> h >> w >> n;
	rep(i, h){
		cin >> maze[i];
		rep(j, w){
			if(maze[i][j] == 'S'){
				sx = j;
				sy = i;
				break;
			}else if(maze[i][j] != 'X' && maze[i][j] !='.'){
				gx[maze[i][j]-'0'] = j;
				gy[maze[i][j]-'0'] = i;
			}
		}
	}
	queue<Data> que;
	que.push(Data(1, sx, sy, 0));
	while(!que.empty()){
		Data data = que.front();que.pop();
		int x = data.x;
		int y = data.y;
		int hp = data.hp;
		int cost = data.cost;
		if(maze[y][x]-'0' == hp)hp++;
		if(hp == n+1){
			FIN(cost);
			break;
		}
		if(memo[hp][y][x] <= cost)continue;
		memo[hp][y][x] = cost;
		rep(i, 4){
			int nx = x + dx[i];
			int ny = y + dy[i];
			if(nx < 0 || ny < 0 || nx >= w || ny >= h || maze[ny][nx] == 'X')continue;
			que.push(Data(hp, nx, ny, cost+1));
		}
	}

	return 0;
}



int StrToInt(string s){
	stringstream ss;
	ss << s;
	int val;
	ss >> val;
	return val;
}
string IntToStr(int i){
	stringstream ss;
	ss << i;
	return ss.str();
}

C++: 
#include <iostream>
#include <algorithm>
#include <stdlib.h>
#include <queue>
using namespace std;

int h,w,n;
char map[1010][1010]={0};
bool flag[1010][1010]={false};
int arr[11][2]={0};
int dir[4][2] = { {1, 0}, {-1, 0}, {0, 1}, {0, -1} };

class node
{
public: 
	node(int x,int y,int s);
	int x;
	int y;
	int s;
};
node::node(int x,int y,int s)
{
	this->x=x;
	this->y=y;
	this->s=s;
}

int bfs(int sx,int sy,int dx,int dy)
{
	queue<node> que;
	node no(sx,sy,0);
	que.push(no);
	flag[sx][sy]=true;
	while(!que.empty())
	{
		node cur=que.front();
		que.pop();
		if(cur.x==dx && cur.y==dy)
			return cur.s;
		for(int i=0;i<4;i++)
		{
			int tx=cur.x+dir[i][0];
			int ty=cur.y+dir[i][1];
			if(map[tx][ty]!='X' && flag[tx][ty] !=true && tx>=0 && tx<h && ty>=0 && ty<w)
			{
				node next(tx,ty,cur.s+1);
				que.push(next);
				flag[tx][ty]=true;
			}
		}
	}
	return -1;
}

int main()
{
	cin>>h>>w>>n;
	for(int i=0;i<h;i++)
		for(int j=0;j<w;j++)
		{
			cin>>map[i][j];
			if(map[i][j]=='S')
			{
				arr[0][0]=i;
				arr[0][1]=j;
				map[i][j]='.';
			}
			else if(isdigit(map[i][j]))
			{
				int d=map[i][j]-'0';
				arr[d][0]=i;
				arr[d][1]=j;
			}
		}
	int ans=0;
	for(int i=0;i<n;i++)
	{
		memset(flag,false,sizeof(flag));
		ans+=bfs(arr[i][0],arr[i][1],arr[i+1][0],arr[i+1][1]);
	}
	cout<<ans<<endl;
	return 0;
}