马走日——最小步数

16 篇文章 0 订阅
14 篇文章 0 订阅

马走日——最小步数

题目描述

       一匹马在一个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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值