Minimum steps to reach target by a Knight
You have been given a square chessboard of size ‘N x N’. The position coordinates of the Knight and the position coordinates of the target are also given.
Your task is to find out the minimum steps a Knight will take to reach the target position.
Example:
knightPosition: {3,4}
targetPosition: {2,1}
The knight can move from position (3,4) to positions (1,3), (2,2) and (4,2). Position (4,2) is selected and the ‘stepCount’ becomes 1. From position (4,2), the knight can directly jump to the position (2,1) which is the target point and ‘stepCount’ becomes 2 which is the final answer.
Note:
1. The coordinates are 1 indexed. So, the bottom left square is (1,1) and the top right square is (N, N).
2. The knight can make 8 possible moves as given in figure 1.
3. A Knight moves 2 squares in one direction and 1 square in the perpendicular direction (or vice-versa).
Input format:
The first line of input contains an integer ‘T’ denoting the number of test cases.
The next ‘3*T’ lines represent the ‘T’ test cases.
The first line of each test case contains a pair of integers denoting the initial position of the knight.
The second line of each input contains a pair of integers denoting the target position.
The third line of each test case contains an integer ‘N’ denoting the rows/columns of the chessboard.
Output format:
For each test case, print an integer representing the minimum steps a Knight will take to reach the target position.
Note :
You do not need to print anything; it has already been taken care of. Just implement the given function.
Constraints
1 <= T <= 10
1 <= N <= 1000
1 <= KNIGHTPOSITION(X, Y), TARGETPOSITION(X, Y) <= N
Time limit: 1 second
CodingNinjas
author
2y
Using BFS
The idea is to perform BFS traversal. Start from the initial position of the Knight and proceed to further cells. Traversal is performed using a queue. The queue stores the different paths t...read more
CodingNinjas
author
2y
Using DP
Let us consider various cases:
1. If the position of the knight and the target cell are along different rows and columns, that is, ‘KNIGHT_X’ is not equal to ‘TARGET_X’ and ‘KNIGHT_Y’ is not e...read more
Help your peers!
Add answer anonymously...
Top Cognizant GenC Next interview questions & answers
Top HR questions asked in Cognizant GenC Next
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app