VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-steps-reach-target-knight/

⇱ Minimum steps to reach target by a Knight | Set 1 - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum steps to reach target by a Knight | Set 1

Last Updated : 23 Jul, 2025

Given a square chessboard of n x n size, the position of the Knight and the position of a target are given. We need to find out the minimum steps a Knight will take to reach the target position.

Examples:

Input: 

👁 kNIGHT
Knight

knightPosition: (1, 3) , targetPosition: (5, 0)

Output: 3
Explanation: In above diagram Knight takes 3 step to reach 
                      from (1, 3) to (5, 0) 
                     (1, 3) -> (3, 4) -> (4, 2) -> (5, 0)  

This problem can be seen as the shortest path in an unweighted graph. Therefore, BFS is an appropriate algorithm to solve this problem. 

Steps:

  • Start with the knight's initial position and mark it as visited.
  • Initialize a queue for BFS, where each entry stores the knight's current position and the distance from the starting position.
  • Explore all 8 possible moves a knight can make from its current position.
  • For each move:
    • Check if the new position is within the board boundaries.
    • Check if the position has not been visited yet.
    • If valid, push this new position into the queue with a distance 1 more than its parent.
  • During BFS, if the current position is the target position, return the distance of that position.
  • Repeat until the target is found or all possible positions are explored.

Output
20

Time complexity: O(n2)
Auxiliary Space: O(n2)

Related Articles:

Minimum steps to reach target by a Knight | Set 2

Comment