马的最小步数

                                          马的最小步数………………数构

 

Description

一匹马在一个8*8的棋盘上走着,它的每一步恰好走成一个日字,也就是在x、y两个方向上,如果在一个方向走一步,另一个方向就走两步。假设棋盘的下标左下角是(1,1),右上角是(8,8)。给你马的最初位置(a,b)各最终位置(an,bn),请你编程求出马从最初位置到最终位置所走的最少步数。

Input

先输入一个正整数T表示有T种情况,每一种情况一行,由四个正整数组成,分别表示a、b、an、bn。

Ouput

每种情况先输出“Case :id”,id是从1开始的序号,然后输出马走的最小步数。

Sample Input

2

1 1 2 3

5 2 5 4

Sample Output

Case 1:1

Case 2:2

Hint

用队列

#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 n,id=1;
	int xs, ys, xe, ye;
	cin >> n;
	for (int i = 1; i <= n; i++) {
		
		while (cin >> xs >> ys >> xe >> ye) {
			for (int i = 1; i <= 8; i++) {
				for (int j = 1; j <= 8; j++) {
					flag[i][j] = false;
				}
			}
			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 <<"Case "<<id++<<":"<< 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;
}

 

 

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值