英文
Time Limit:1s Memory Limit:256M
Description
Please calculate the least steps knight moves from one position to another.
Input
The first line is an integer n,represent a n*n chess board(x is 0 to n-1,y is 0 to n-1),
The next two lines,each line contains two integer represent the start position and the end position. 1<=n<=300
Output
An integer
Sample Input
100
0 0
30 50
Sample Output
28
中文
时间:1s 空间:256M
题目描述:
国际象棋中的骑士(走日字型),从棋盘上一个点走到另一个点最少需要几步。
输入格式:
第一行输入一个整数n,表示棋盘的大小为n∗n,棋盘两个维度的坐标都是从0到n-1
接下来两行每行两个整数分别表示出发点的坐标与终点的坐标。
输出格式:
输出一个整数,表示最小步数
样例输入:
100
0 0
30 50
样例输出:
28
约定:
1<=n<=300
提示:
这道题求的是最优解,很容易就想到广度优先搜索(又称宽度优先搜,BFS),最先在队列里遇到的答案一定就是最优解了。广度优先搜索用队列实现,用队列的left来扩展right来维持搜索。具体代码如下:
代码:
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <cmath>
#include <algorithm>
#define N 300
using namespace std ;
struct mrz
{
int x , y , z ; //z是用来记录第一次扫到时的步数,即当前坐标的最短步数
} p [ N * N + 1 ] ;
int x_c , y_c , x_z , y_z , n , l = 1 , r = 1 ;
bool mp [ N + 1 ] [ N + 1 ] ; //记录是否到达过该点
bool pd ( int k1 , int k2 )