写程序,计算象棋中马从一个位置移动到另一个位置所需的最少移动次数
输入格式
有多组测试数据。
第一行一个整数 T,代表数据组数。
每组数据包含三行。
第一行表示棋盘的长度 L,棋盘大小为 L×L。
第二行包含两个整数 x, y,表示马的起始位置坐标。
第三行包含两个整数 a, b,表示马的终点位置坐标。
L 最大为 300。
棋盘坐标范围为 [0, …, L-1]。
输出格式
对于每组数据输出一行,包含一个数字,即最少移动次数。
若起点终点相同,则移动次数为 0。
输入样例 复制
3
8
0 0
7 0
100
0 0
30 50
10
1 1
1 1
输出样例 复制
5
28
0
马走日!!!
BFS 广度优先
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
struct posi
{
int x;
int y;
posi(int x1, int y1)
{
x = x1;
y = y1;
}
};
int dis[301][301],backup1[301][301];
bool visted[301][301],backup2[301][301];
int xl[8] = { -2,-1,1,2,2,1,-1,-2 };
int yl[8] = { 1,2,2,1,-1,-2,-2,-1 };
int check_boundary(int sizes,posi temp)
{
if (temp.x >= 0 && temp.x < sizes && temp.y >= 0 && temp.y < sizes)
return 1;
return 0;
}
int main()
{
int times;
cin >> times;
int x, y, a, b;
while (times--)
{
int sizes;
cin >> sizes;
memcpy(dis, backup1, sizeof backup1);
memcpy(visted, backup2, sizeof backup2);
cin >> x >> y >> a >> b;
dis[x][y] = 0;
visted[x][y] = 1;
queue<posi>q;
q.push(posi(x, y));
while (!q.empty())
{
posi temp = q.front();
q.pop();
if (temp.x == a && temp.y == b)
cout << dis[a][b] << endl;
else
{
int x_temp, y_temp;
for (int i = 0; i < 8; i++)
{
x_temp = temp.x+xl[i];
y_temp = temp.y+yl[i];
posi temps(x_temp, y_temp);
if (check_boundary(sizes, temps) && !visted[x_temp][y_temp])
{
q.push(temps);
visted[x_temp][y_temp] = 1;
dis[x_temp][y_temp] = dis[temp.x][temp.y] + 1;
}
}
}
}
}
return 0;
}