题目:http://acm.hdu.edu.cn/showproblem.php?pid=1372
大意:至少要用多少步,骑士才能从给定位置到达另一个位置。(骑士的走法和象棋里的马的走法是一样的,均是日字型)
Sample Input
Sample Output
To get from e2 to e4 takes 2 knight moves. To get from a1 to b2 takes 4 knight moves. To get from b2 to c3 takes 2 knight moves. To get from a1 to h8 takes 6 knight moves. To get from a1 to h7 takes 5 knight moves. To get from h8 to a1 takes 6 knight moves. To get from b1 to c3 takes 1 knight moves. To get from f6 to f6 takes 0 knight moves.
显然,这需要BFS。
BFS核心是一次性先把所有最近的能走的统统遍历,然后再去遍历其他的点。这和队列联系在一起了,近点先进,远点后进,对队列的遍历就相当于层次遍历了。比如这个二叉树的层次遍历:
代码: