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++: //待解，&#35843;用函数 
#include <queue> 
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
typedef struct{
	int x,y;
	int time;
}Mouse;
const int maxn = 1005;
int height,width,n;    //n代表硬度 
char maze[maxn][maxn];
int dx[] = {0,1,0,-1};
int dy[] = {-1,0,1,0};
bool visited[maxn][maxn];
int shortDistance(int sx,int sy,int ex,int ey)
{
	//初始化visted数&#32452;
	for(int i = 0;i<height;i++)
		for(int j = 0;j<width;j++)
			visited[i][j] = false;
	visited[sx][sy] = true;
	queue<Mouse> q;
	Mouse m;
	m.x = sx;m.y = sy;m.time = 0;
	q.push(m);
	while(q.size())
	{
		Mouse t = q.front();q.pop();
		if(t.x==ex&&t.y==ey)
		{
			return t.time;
		}
		for(int i = 0;i<4;i++)
		{
			int nx = t.x + dx[i];
			int ny = t.y + dy[i];
			if(nx>=0&&nx<width&&ny>=0&&ny<height&&maze[ny][nx]!='X'&&!visited[nx][ny])
			{
				Mouse a;
				a.x = nx;a.y = ny;a.time = t.time+1;
			 		maze[ny][nx] = '.';
			 	visited[nx][ny] = true;
				q.push(a);
			}
		}
	}
}

int main()
{
	int cx[10],cy[10];
	int cnt = 0;
	bool flag = true; 
	scanf("%d%d%d",&height,&width,&n);
	getchar();//清除回&#36710; 
	//&#36755;入迷&#23467; 
	for(int i = 0;i<height;i++)
	{
		fgets(maze[i],maxn,stdin);
		//&#26597;找老鼠&#24034;的位置
		int len = strlen(maze[i]);
		for(int j = 0;j<len;j++)
		if(flag&&strchr("123456789S",maze[i][j]))
		{
			cnt++;
			if(cnt==n+1)flag = false;
			if(maze[i][j]=='S')
			{
				cy[0] = i;
				cx[0] = j;
			}
			else 
			{
				int k = maze[i][j]-'0';
				cx[k] = j;cy[k] = i; 
			}
			
		}
	}
	int cost = 0;
	for(int i = 0;i<n;i++)
		cost += shortDistance(cx[i],cy[i],cx[i+1],cy[i+1]);
	cout << cost <<endl;
	return 0;
}

C++: #include <cstdio>
#include <cmath>
#include <algorithm>
#include <queue>
#include <iostream>
#include <vector>
#include <cstdlib>
#include <cstring>
#define eps 1e-6
#define ll long long
#define INF 0x3f3f3f3f
using namespace std;

char map[1005][1005];
int dis[1005][1005];
int dx[] = {0,0,1,-1};
int dy[] = {1,-1,0,0};
int row,col,n;
int current = 1;
int firstX,firstY;
int ans = 0;
typedef pair<int,int> pos;
queue <pos> q;

void bfs(){
    while(q.size()){
        pos t = q.front();
        q.pop();
        if(map[t.first][t.second] - '0'== current){
            ans += dis[t.first][t.second];
            current++;
            //清空队列保证下次起点正常
            while(q.size()){
                q.pop();
            }
            //重置距离数组
            memset(dis,INF,sizeof dis);
            dis[t.first][t.second] = 0;
            //设置下一次广搜的起点
            q.push(pos(t.first,t.second));
        }
        //四个方向进行bfs
        for(int i = 0;i<4;i++){
            int x = t.first + dx[i];
            int y = t.second + dy[i];
            if(x<0 || x>= row || y < 0|| y>=col || map[x][y] == 'X' || dis[x][y] != INF)//INF判断是否走过
                continue;
            else{
                q.push(pos(x,y));
                dis[x][y] = dis[t.first][t.second] + 1;
            }
        }
    }
}

int main(){
    cin>>row>>col>>n;
    //初始化
    ans = 0;
    memset(dis,INF,sizeof dis);
    for(int i = 0;i<row;i++){
        for(int j = 0;j<col;j++){
            cin>>map[i][j];
            if(map[i][j] == 'S'){
                //设置起点
                q.push(pos(i,j));
                dis[i][j] = 0;
            }
        }
    }
    //开始广搜
    bfs();
    cout<<ans<<endl;
    return 0;
}

C++: #include <iostream>
#include <queue>
#include <climits>
#define REP(i,n) for(int i=0;i<(n);i++)
using namespace std;

typedef pair<int,int> pii;

int main()
{
  int H, W, N;
  const int dx[] = {1, 0, -1, 0}, dy[] = {0, 1, 0, -1};
  cin >> H >> W >> N;
  char map[H][W];
  int d[N][H][W], hp = 1, ans = 0;
  fill(d[0][0],d[N][0],INT_MAX);
  queue<pii> q;
  REP(i,H){
    REP(j,W){
      cin >> map[i][j];
      if(map[i][j] == 'S'){
        q.push({i,j});
        d[hp-1][i][j] = 0;
      }
    }
  }
  while(1){
    pii p = q.front();
    q.pop();
    if(hp == map[p.first][p.second]-'0'){
      ans += d[hp-1][p.first][p.second];
      hp++;
      d[hp-1][p.first][p.second] = 0;
      while(!q.empty()) q.pop();
    }
    if(hp == N+1){
      cout << ans << endl;
      return 0;
    }
    REP(i,4){
      pii next_p = {p.first+dx[i],p.second+dy[i]};
      if(next_p.first < 0 || next_p.first >= H || next_p.second < 0 || next_p.second >= W || map[next_p.first][next_p.second] == 'X') continue;
      if(d[hp-1][next_p.first][next_p.second] > d[hp-1][p.first][p.second]+1){
        d[hp-1][next_p.first][next_p.second] = d[hp-1][p.first][p.second]+1;
        q.push(next_p);
      }
    }
  }
}

C++: #include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
#include<vector>
#include<set>
using namespace std;
typedef long long ll;
int H,W,N;
char mm[1005][1005];
bool v[1005][1005];
int xx,yy;
struct node{
    int x,y,step;
};
queue<node> que;
int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};
bool check(int x,int  y){
    if(1<=x&&x<=H&&1<=y&&y<=W&&!v[x][y]&&mm[x][y]!='X')return true;
    else return false;
}
int bfs(int g){
    while(!que.empty())que.pop();
    node t;
    t.x=xx;
    t.y=yy;
    t.step=0;
    v[xx][yy]=1;
    que.push(t);
    while(!que.empty()){
        t=que.front();
        que.pop();
        for(int i=0;i<4;i++){
            int nx=t.x+dx[i];
            int ny=t.y+dy[i];
            if(check(nx,ny)){
                if(mm[nx][ny]==g+'0'){
                    xx=nx;
                    yy=ny;
                    return t.step+1;
                }
                node tt;
                tt.x=nx;
                tt.y=ny;
                tt.step=t.step+1;
                v[nx][ny]=1;
                que.push(tt);
            }
        }
    }
}
int main(){
    while(~scanf("%d%d%d",&H,&W,&N)){
        for(int i=1;i<=H;i++){
            scanf("%s",mm[i]+1);
        }
        for(int i=1;i<=H;i++){
            for(int j=1;j<=W;j++){
                if(mm[i][j]=='S'){
                    xx=i;
                    yy=j;
                }
            }
        }
        int ans=0;
        for(int i=1;i<=N;i++){
            memset(v,0,sizeof(v));
            ans+=bfs(i);
        }
        printf("%d\n",ans);
    }
    return 0; 
}