Problem E 马的最短路径
Description
在一个8*8的棋盘上有三个位置马不能到,它们是(2,2)、(7,7)、(4,4)。棋盘的左下角是(1,1),右上角是(8,8)。给你最初的位置(xs,ys),最终的位置(xe,ye)请编程求出马的最小步数。
Input
有多组测试数据,每组一行,有4个整数,xs,ys,xe,ye。
Ouput
输出最小步数。
Sample Input
1 1 3 3
Sample Output
5
如图所示:
实验代码:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <queue>
using namespace std;
int direction[8][2] = { { 2, 1 },{ 1, 2 },{ -1, 2 },
{ -2, 1 },{ -2, -1 },{ -1, -2 },{ 1, -2 },{ 2, -1 } }; //方向
bool flag[9][9];//标记是否走过
struct Horse {
int x;
int y;
int step;
};
int main()
{
int xs, ys, xe, ye;
while (cin >> xs >> ys >> xe >> ye) {
struct Horse hs;
hs.x = xs; hs.y = ys; hs.step = 0;
queue <Horse> lq;
lq.push(hs);
while (!lq.empty()) {
struct Horse hs1;
hs1.x = lq.front().x;
hs1.y = lq.front().y;
hs1.step = lq.front().step;
lq.pop();
if (hs1.x == xe && hs1.y == ye) {
cout << hs1.step << endl;;
}
else {
for (int z = 0; z < 8; z++) {
struct Horse ho;
ho.x = hs1.x + direction[z][0];
ho.y = hs1.y + direction[z][1];
ho.step = hs1.step + 1;
if (ho.x >= 1 && ho.x <= 8 && ho.y >= 1
&& ho.y <= 8
&& flag[ho.x][ho.y] == false) {
lq.push(ho);
flag[ho.x][ho.y] = true;
}
}
}
}
}
return 0;
}