The horse in the chessboard
There is a horse in the chessboard. Give its position. It has a destination. How many steps does it need to go to its destination.
input
• input: the first line has two integers: n,m, (n < = 1000, m < = 1000) indicating that the chessboard has n lines and m columns. The first row and the first column are (1,1) • the second line: x1, y1, indicating the position of the horse. • the third line, x2, y2, indicates its destination. Ensure that the start and end positions are in the chessboard. If the horse cannot reach the destination, output - 1
output
The minimum number of steps required for a horse to reach its destination
sample input
3 5 2 5 1 1
sample output
3
The code is as follows
#include<cstdio>
int quex[1000005],quey[1000005],ques[1000005];
int dr[8][2]={{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1}};
//dr is the direction array, quex, quey, ques is the queue array (can use structure), ques is the number of extended layers
bool book[1005][1005],flag;
//book marks the passing points, flag is used to determine whether to find, and exit the loop
int main()
{
int n,m,x1,y1,x2,y2,xx,yy,head,tail;
head=tail=1;
//The starting value of team head and team tail is 1
scanf("%d%d",&n,&m);
scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
quex[tail]=x1;
quey[tail]=y1;
ques[tail]=0;
tail++;
//Enter the starting point coordinate into the team, and the tail points to the last element of the team
book[x1][y1]=1;
//Mark starting point
while(head<tail)
//Exit loop when team head and tail point to the same position
{
for(int i=0;i<8;i++)
//Enumerate 8 directions
{
xx=quex[head]+dr[i][0];
yy=quey[head]+dr[i][1];
if(xx>0&&yy>0&&xx<=n&&yy<=m&&book[xx][yy]==0)
{
book[xx][yy]=1;
//Mark the passing point
quex[tail]=xx;
quey[tail]=yy;
ques[tail]=ques[head]+1;
tail++;
//Put the current coordinates in the team, and the tail points to the next element at the end of the team,
//The number of layers is the number of layers of the node to be expanded + 1
}
if(xx==x2&&yy==y2){flag=1;break;}
//When the horse reaches the end, exit the cycle
}
if(flag==1)break;
//If found, exit the loop
head++;
//End of extension, change to the next extension
}
if(flag==0)printf("-1");
else printf("%d",ques[tail-1]);
//When flag=0, it is not found, because tail always points to the last element at the end of the team, so subtract 1
return 0;
}