马的最小步数

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

Accepted: 1151    Total Submit: 1830
Time Limit: 1000ms    Memony Limit: 32768KB

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


猜你喜欢

转载自blog.csdn.net/yky__xukai/article/details/80325637