马走日——最小步数
题目描述
一匹马在一个8*8的棋盘上走着,它的每一步恰好走成一个日字,也就是在x、y两个方向上,如果在一个方向走一步,另一个方向就走两步。假设棋盘的下标左下角是(1,1),右上角是(8,8)。给你马的最初位置p1(a1,b1),最终位置p2(a2,b2),请你编程求出马从最初位置到最终位置所走的最少步数。
#include<iostream>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
struct point
{
int a;
int b;
int step;
point(int x, int y, int s = 0)
{
a = x;
b = y;
step = s;
}
};
bool isCheck(point p)
{
if (p.a >= 0 && p.a <= 8 && p.b >= 0 && p.b <= 8)
return true;
else
return false;
}
void bfs(point &p1, point &p2, vector<point> &pvec, vector<vector<bool>> &flag)
{
queue<point> q;
q.push(p1);
while (!q.empty())
{
point temp1(q.front().a, q.front().b, q.front().step);
q.pop();
if (temp1.a == p2.a && temp1.b == p2.b)
cout << temp1.step << endl;
else
{
for (int i = 0; i < 8; i++)
{
point temp2(temp1.a + pvec[i].a, temp1.b + pvec[i].b);
temp2.step = temp1.step + 1;
if (isCheck(temp2) && flag[temp2.a][temp2.b])
{
q.push(temp2);
flag[temp2.a][temp2.b] = false;
}
}
}
}
}
int main()
{
int x1, y1;
int x2, y2;
while (cin >> x1 >> y1 >> x2 >> y2)
{
point A(x1, y1);
point B(x2, y2);
vector<point> pvec = { { 1, 2 }, { 1, -2 }, { 2, 1 }, { 2, -1 }, { -1, 2 }, { -1, -2 }, { -2, 1 }, { -2, -1 } };
vector<vector<bool>> flag(9, vector<bool>(9, true));
bfs(A, B, pvec, flag);
}
return 0;
}