Asked inIQVIA,SDE-2
Minimum steps taken by knight to reach target

You are given a 2D matrix of size N x N which is nothing but a square chessboard. Given the starting and target positions of the knight, you are supposed to return the minimum number of steps required by the knight to reach the target position from the given starting point.

Note :
Following is the possible movements of the knight from a particular position.

alt text

Input Format :
 The first line of input contains an integer 'T' representing the number of the test case. Then the test cases are as follows.

 The first line of each test case contains one integer ‘N’ representing the side of the square chessboard or 2D matrix.

 The second line contains two integers ‘SX’ and ‘SY’ representing the starting position of the knight in the chessboard.

 The third line contains two integers ‘TX’ and ‘TY’ representing the target position in the chessboard.
Output Format :
For each test case, return the minimum number of steps taken by the knight to reach the target position from the given starting position.
Note :
You do not need to print anything; It has already been taken care of. 
Constraints :
1 ≤ T ≤ 50
1 ≤ N ≤ 100
1 ≤ SX,SY,TX,TY ≤ 100

Where ‘T’ is the number of test cases.
‘N’ is the side of the given chessboard or matrix.
‘SX’, ‘SY’, ‘TX’, ‘TY’ denotes the starting and target positions in the given chessboard.

Time Limit: 1 sec
CodingNinjas
author
2y
Breadth-First Search

Our intuition is to think of all the positions knight can reach from the current position. This problem can be seen as the shortest path in an unweighted graph. Hence, we use BFS t...read more

CodingNinjas
author
2y
Dynamic Programming

Take a close look at the positions of the knight and the target and how will it get affected in different cases:

First of all, let’s talk about the non-linear positions where the kni...read more

Help your peers!
Add answer anonymously...
IQVIA 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
Get AmbitionBox app

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