Asked inCisco,SDE-2

Minimum Steps for a Knight to Reach Target

Given a square chessboard of size 'N x N', determine the minimum number of moves a Knight requires to reach a specified target position from its initial position.

Explanation:

Your task is to calculate the least number of moves a Knight needs to move from its starting position to the target position on an NxN chessboard.

Input:

The first line consists of an integer ‘T’ indicating the number of test cases.
The subsequent ‘3*T’ lines include the ‘T’ test cases:
The first line of each test contains two integers marking the Knight's starting position.
The second line contains two integers identifying the target position.
The third line consists of an integer 'N', representing the chessboard's size.

Output:

For every test case, output an integer that signifies the minimum number of moves required for the Knight to arrive at the target position.

Example:

Input:
knightPosition: {3,4}
targetPosition: {2,1}
Output:
2
Explanation:

The Knight can move from position (3,4) to positions (1,3), (2,2), and (4,2). Selecting position (4,2), the 'stepCount' becomes 1. From (4,2), the Knight directly jumps to (2,1), achieving the target, and the 'stepCount' becomes 2, which is the final outcome.

Constraints:

  • 1 <= T <= 10
  • 1 <= N <= 1000
  • 1 ≤ KNIGHTPOSITION(X, Y), TARGETPOSITION(X, Y) ≤ N
Note:
  • The board is referenced as 1 indexed (bottom left is (1,1) and top right is (N,N)).
  • The Knight can execute 8 potential movements as depicted.
  • A Knight transitions by moving 2 squares in one direction and a single square in a perpendicular direction (or vice-versa).
  • Printing is not required; simply implement the given function.
Be the first one to answer
Add answer anonymously...
Cisco SDE-2 Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
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

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter