题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=1372

题目描述

A friend of you is doing research on the Traveling Knight Problem (TKP) where you are to find the shortest closed tour of knight moves that visits each square of a given set of n squares on a chessboard exactly once. He thinks that the most difficult part of the problem is determining the smallest number of knight moves between two given squares and that, once you have accomplished this, finding the tour would be easy.
Of course you know that it is vice versa. So you offer him to write a program that solves the “difficult” part.

Your job is to write a program that takes two squares a and b as input and then determines the number of knight moves on a shortest route from a to b.

思路

BFS+优先队列,直接写。

AC代码

/*************************************************************************
    > File Name: 1372.cpp
      > Author: Netcan
      > Blog: http://www.netcan.xyz
      > Mail: 1469709759@qq.com
      > Created Time: Wed 20 May 2015 11:46:21 AM CST
 ************************************************************************/

#include <iostream>
#include <vector>
#include <string>
#include <queue>
#include <algorithm>
#include <cmath>
#include <ctime>
#include <cstdio>
#include <sstream>
#include <deque>
#include <functional>
#include <iterator>
#include <list>
#include <map>
#include <memory>
#include <stack>
#include <set>
#include <numeric>
#include <utility>
#include <cstring>
using namespace std;

struct point { // 状态
    int i, j, step; // 坐标i, j,步数step
    point(int i, int j, int step): i(i), j(j), step(step) {} // 构造函数
    point() {}
    friend bool operator<(const point &a, const point &b) { // 设置优先级
        return a.step > b.step;
    }
};
point s, e; // 起点终点
int direct[][2] = {{1, 2}, {1, -2}, {2, 1}, {2, -1},
	           {-1, 2}, {-1, -2}, {-2, 1}, {-2, -1}}; // 跳的位置
bool visited[10][10]; // 记录已跳过的地方

int bfs() {
    priority_queue<point> que;    // 优先队列
    memset(visited, 0, sizeof(visited)); 
    que.push(point(s.i, s.j, 0)); // 起点入队
    while(que.size()) {
        point p = que.top();
        que.pop();
        if(p.i == e.i && p.j == e.j) // 到达终点
            return p.step;
        for(int k=0; k<8; ++k) { 
            int nx = p.i + direct[k][0];
            int ny = p.j + direct[k][1];
            if(nx >=1 && nx<=8 && ny>=1 && ny<=8 && !visited[nx][ny] ) {
                que.push(point(nx, ny, p.step + 1)); // 可跳则跳
                visited[nx][ny] = true;
            }
        }
    }
    return -1; // 无法到达终点
}

int main()
{
#ifdef Oj
    freopen("1372.data", "r", stdin);
#endif
    string a, b;
    while(cin >> a >> b) {
        s.i = a[0]-'a' + 1;
        s.j = a[1]-'0';
        e.i = b[0]-'a' + 1;
        e.j = b[1]-'0';
        printf("To get from %s to %s takes %d knight moves.\n", 
        a.c_str(), b.c_str(), bfs());
    }
    return 0;
}