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<queue>
using namespace std;
struct Data{
    int x;
    int y;
    int t;
};
bool vis[1005][1005];
const int dx[] = {1,0,-1,0},dy[] = {0,1,0,-1};
int main(){
    int h,w,n;
    cin>>h>>w>>n;
    string fi[1020];
    Data init;
    for(int i = 0;i < h;i++){
        cin>>fi[i];
        for(int j = 0;j < w;j++){
            if(fi[i][j] == 'S'){
                init.x = j;
                init.y = i;
            }
        }
    }
    init.t = 0;

    queue<Data> Q;
    Q.push(init);
    int now = 1;
    while(!Q.empty()){
        Data D = Q.front();
        Q.pop();
        D.t++;
        if(vis[D.y][D.x])continue;
        if(fi[D.y][D.x] == now + '0'){
            now++;
            for(int i = 0;i < h;i++){
                for(int j = 0;j < w;j++){
                    vis[i][j] = false;
                }
            }
            Q = queue<Data>();
            Q.push(D);
        }
        vis[D.y][D.x] = true;
        if(now == n+1){
            cout<<D.t-1<<endl;
            return 0;
        }
        for(int i = 0;i < 4;i++){
            int x = D.x + dx[i];
            int y = D.y + dy[i];
            if(0 <= x&&x < w&&0 <= y&& y < h){
                if(fi[y][x] == 'X')continue;
                if(vis[y][x])continue;
                Data E = D;
                E.x = x, E.y = y;
                Q.push(E);
            }
        }
    }
}

C++: #include<bits/stdc++.h>
#define x first
#define y second
#define u(i,a,b) for(int i=a;i<b;i++)
using namespace std;pair<int,int> p[12];bool t[1010][1010],v[1010][1010];queue<pair<int,pair<int,int> > >Q;int main(){int h,w,k,a=0,dx[]={0,1,0,-1},dy[]={1,0,-1,0};cin>>h>>w>>k;u(i,0,h)u(j,0,w){t[i][j]=1;char z;cin>>z;if(z=='X')t[i][j]=0;if(z=='S')p[0]=make_pair(i,j);if(z>'0'&&z<='9')p[z-'0']=make_pair(i,j);}u(r,0,k){Q.push(make_pair(0,p[r]));u(i,0,h)u(j,0,w)v[i][j]=0;v[p[r].x][p[r].y]=1;while(1){int L=Q.front().x,Y=Q.front().y.x,X=Q.front().y.y;if(Y==p[r+1].x&&X==p[r+1].y){a+=L;break;}u(i,0,4){int f=Y+dy[i],g=X+dx[i];if(f>=0&&f<h&&g>=0&&g<w){if(t[f][g]==1&&v[f][g]==0){v[f][g]=1;Q.push(make_pair(L+1,make_pair(f,g)));}}}Q.pop();}while(!Q.empty())Q.pop();}cout<<a<<endl;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};
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(1)
	{
		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;
	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;的位置
		for(int j = 0;j<width;j++)
		{
			if(maze[i][j]=='S')
			{
				cy[0] = i;
				cx[0] = j;
			}
			else if(isdigit(maze[i][j]))
			{
				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 <iostream>
#include <vector>
#include <climits>
#include <algorithm>

using namespace std;

const int dir[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

void solve(vector<vector<char> >& board, int H, int W, int N, 
           int x, int y, int power, int count, int step, int& ret) {
  int prev_value = board[x][y];
  if (step >= ret) return;
  if (board[x][y] >= 1 && board[x][y] <= 9) {
    power++;
    count++;
    board[x][y] = '.';
    if (count == N) {
      ret = min(ret, step);
      board[x][y] = prev_value;
      return;
    }
  }

  //board[x][y] = 'X';
  for (int i = 0; i < 4; ++i) {
    int next_x = x + dir[i][0];
    int next_y = y + dir[i][1];
    if (next_x >= 0 && next_x < H
        && next_y >= 0 && next_y < W
        && board[next_x][next_y] != 'X') {
        if (board[next_x][next_y] >= 1 
            && board[next_x][next_y] < 9
            && power < board[next_x][next_y]) 
          continue;
        solve(board, H, W, N, next_x, next_y, power, count, step + 1, ret);
    }
  }
  board[x][y] = prev_value;
}

int main() {
  int H, W, N;
  cin >> H >> W >> N;
  vector<vector<char> > board(H, vector<char>(W));
  char c;
  int x, y;
  for (int h = 0; h < H; ++h) {
    for (int w = 0; w < W; ++w) {
      cin >> c;
      if (c >= '1' && c <= '9') {
        c = c - '0';
      }
      board[h][w] = c;
      if (c == 'S') {
        x = h;
        y = w;
      }
    }
  }
  int ret = H * W;
  board[x][y] = '.';
  solve(board, H, W, N, x, y, 1, 0, 0, ret);
  cout << ret << endl;
}

C++: #include <bits/stdc++.h>

using namespace std;
typedef long long int ll;
typedef pair<int, int> P;
typedef pair<ll, ll> Pll;
typedef vector<int> Vi;
typedef tuple<int, int, int> T;
#define FOR(i,s,x) for(int i=s;i<(int)(x);i++)
#define REP(i,x) FOR(i,0,x)
#define ALL(c) c.begin(), c.end()
#define DUMP( x ) cerr << #x << " = " << ( x ) << endl

const int INF = 1<<29;
const int dr[4] = {-1, 0, 1, 0};
const int dc[4] = {0, 1, 0, -1};

int H, W, N;
int D[16];
string town[1024];
int dist[1024][1024];
P factory[16];

inline bool in(int r, int c) {
  return 0 <= r && r < H && 0 <= c && c < W;
}

int main() {
  // use scanf in CodeForces!
  cin.tie(0);
  ios_base::sync_with_stdio(false);

  cin >> H >> W >> N;
  REP(i, H) cin >> town[i];
  int sr = 0, sc = 0;
  REP(i, H) REP(j, W) {
    if (town[i][j] == 'S') {
      sr = i, sc = j;
      break;
    }
  }

  int ans = 0;
  REP(i, N) {
    REP(r, H) REP(c, W) dist[r][c] = -1;
    queue<T> que;
    que.push(T(sr, sc, 0));
    while (!que.empty()) {
      int r, c, d;
      tie(r, c, d) = que.front(); que.pop();
      if (dist[r][c] != -1) continue;
      dist[r][c] = d;
      if (town[r][c] != 'S' && town[r][c] != '.' && town[r][c] != 'X' && town[r][c] - '0' == i+1) {
	ans += d;
	sr = r, sc = c;
	break;
      }
      REP(j, 4) {
	int nr = r + dr[j], nc = c + dc[j];
	if (in(nr, nc) && town[nr][nc] != 'X' && dist[nr][nc] == -1) {
	  que.push(T(nr, nc, d+1));
	}
      }
    }
  }

  cout << ans << endl;      
  return 0;
}