马的最短路径(有障碍)

                                           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;
}

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值