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<string>
#include<vector>
using namespace std;
int xs[10],ys[10];
int H,W,N;
string S[1002];
int main()
{
	scanf("%d%d%d",&H,&W,&N);
	for(int i=0;i<W+2;i++){
		S[0]+='X';
		S[H+1]+='X';
	}
	for(int i=1;i<=H;i++){
		string x;
		cin >> x;
		S[i]+='X'+x+'X';
	}
	for(int i=1;i<=H;i++){
		for(int j=1;j<=W;j++){
			if(S[i][j]!='X'&&S[i][j]!='.'){
				if(S[i][j]=='S'){
					xs[0]=j;
					ys[0]=i;
				}
				else{
					xs[S[i][j]-'0']=j;
					ys[S[i][j]-'0']=i;
				}
			}
		}
	}
	int XX[1002][1002];
	int ans=0;
	vector<pair<int,int> >vec1;
	vector<pair<int,int> >vec2;
	int dx[4]={-1,0,0,1};
	int dy[4]={0,-1,1,0};
	for(int x=0;x<N;x++){
		vec1.clear();
		vec2.clear();
		for(int i=0;i<H+2;i++)for(int j=0;j<W+2;j++)XX[i][j]=-1;
		int cou=0;
		XX[ys[x]][xs[x]]=cou;
		vec1.push_back(make_pair(ys[x],xs[x]));
		while(XX[ys[x+1]][xs[x+1]]==-1){
			vec2.clear();
			for(int i=0;i<vec1.size();i++){
				for(int j=0;j<4;j++){
					if(S[vec1[i].first+dy[j]][vec1[i].second+dx[j]]=='X')continue;
					if(XX[vec1[i].first+dy[j]][vec1[i].second+dx[j]]!=-1)continue;
					vec2.push_back(make_pair(vec1[i].first+dy[j],vec1[i].second+dx[j]));
				}
			}
			vec1.clear();
			for(int i=0;i<vec2.size();i++)vec1.push_back(vec2[i]);
			cou++;
			for(int i=0;i<vec1.size();i++){
				XX[vec1[i].first][vec1[i].second]=cou;
			}
		}
		ans+=XX[ys[x+1]][xs[x+1]];
	}
	printf("%d\n",ans);
	return 0;
}

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};

int shortDistance(int sx,int sy,int ex,int ey)
{
	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')
			{
				Mouse a;
				a.x = nx;a.y = ny;a.time = t.time+1;
			 		maze[ny][nx] = '.';
				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<bits/stdc++.h>
using namespace std;
int h,w,n;
int sakuya=0,mn=100000;
int ans=0;
int px[4]={0,1,0,-1};
int py[4]={1,0,-1,0};
int sx,sy;
char box[1001][1001],check[1001][1001];
char num='0';
queue<int>que;

void deep(int nx,int ny);
int main(){
  cin>>h>>w>>n;
  for(int i=1;i<=h;i++){
    for(int j=1;j<=w;j++){
      cin>>box[i][j];
      // first start point set
      if(box[i][j]=='S'){
	sx=i;
	sy=j;
      }
      check[i][j]=box[i][j];
    }
  }

  for(int i=1;i<=n;i++){
    num++;
    deep(sx,sy);
    ans+=mn;
    mn=100000;
    sakuya=0;
  }
  cout<<ans<<endl;
  return(0);
}

void deep(int x,int y){
  if(box[x][y]==num){
    if(mn>sakuya)mn=sakuya;
    sx=x;
    sy=y;
  }
  else{
    for(int i=0;i<4;i++){
      check[x][y]='X';
      x+=px[i];
      y+=py[i];
      sakuya++;
      if(x>0 && y>0 && x<=h && y<=w && check[x][y]!='X'){
	deep(x,y);
      }
      sakuya--;
      x-=px[i];
      y-=py[i];
      check[x][y]='.';
    }
  }
}

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

using namespace std;

const int hw_max = 1000 + 5;
char graph[hw_max][hw_max];
int sign[hw_max][hw_max];
int h, w, n, ans;
int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, -1, 1};
struct node
{
    int x;
    int y;
    int time;
} start;

void BFS(node op, char ed)
{
    queue <node> process;
    process.push(op);
    sign[op.x][op.y] = 1;
    while(!process.empty())
    {
        node now = process.front();
        process.pop();
        for(int i = 0; i < 4; i ++)
        {
            node next = now;
            next.x += dx[i];
            next.y += dy[i];
            next.time ++;
            if(next.x >= 0 && next.x < h && next.y >= 0 && next.y < w && graph[next.x][next.y] != 'X' && !sign[next.x][next.y])
            {
                if(graph[next.x][next.y] == ed)
                {
                    ans += next.time;
                    next.time = 0;
                    start = next;
                        return;
                }
                else
                {
                    process.push(next);
                    sign[next.x][next.y] = 1;
                }
            }
        }
    }
}

int main()
{
    while(~scanf("%d %d %d", & h, & w, & n))
    {
        getchar();
        for(int i = 0; i < h; i ++)
        {
            for(int j = 0; j < w; j ++)
            {
                   scanf("%c", & graph[i][j]);
                   if(graph[i][j] == 'S')
                   {
                    start.x = i;
                    start.y = j;
                    start.time = 0;
                   }
            }
            getchar();
        }
        ans = 0;
        for(int i = 1; i <= n; i ++)
        {
            memset(sign, 0, sizeof(sign));
            BFS(start, '0' + i);
        }
        printf("%d\n", ans);
    }
    return 0;
}