Chess Knight Problem | Find Shortest path from source to destination

Given a chess board, find the shortest distance (minimum number of steps) taken by a Knight to reach given destination from given source.


For example,

Input: N = 8 (8 x 8 board), Source = (7, 0) Destination  = (0, 7)

Output: Minimum number of steps required is 6

Explanation: The Knight’s movement can be demonstrated in figure below




The idea is to use BFS as it is a Shortest Path problem. Below is the complete algorithm.

1. Create an empty queue and enqueue source cell having
   distance 0 from source (itself)

2. do till queue is not empty

   a) Pop next unvisited node from queue

   b) If the popped node is destination node, return its distance

   c) else we mark current node as visited and for each of 8 possible
      movements for a knight, we enqueue each valid movement into the
      queue with +1 distance (min distance of given node from source
      = min distance of parent from source + 1)

A knight can move in 8 possible directions from a given cell as illustrated in below figure –


We can find all the possible locations the Knight can move to from the given location by using the array that stores the relative position of Knight movement from any location. For example, if the current location is (x, y), we can move to (x + row[k], y + col[k]) for 0 <= k <=7 using below array.

row[] = [ 2, 2, -2, -2, 1, 1, -1, -1 ]
col[] = [ -1, 1, 1, -1, 2, -2, 2, -2 ]

So, from position (x, y) Knight’s can move to:

(x + 2, y – 1)
(x + 2, y + 1)
(x – 2, y + 1)
(x – 2, y – 1)
(x + 1, y + 2)
(x + 1, y – 2)
(x – 1, y + 2)
(x – 1, y – 2)

Note that in BFS, all cells having shortest path as 1 are visited first, followed by their adjacent cells having shortest path as 1 + 1 = 2 and so on.. so if we reach any node in BFS, its shortest path = shortest path of parent + 1. So, the first occurrence of the destination cell gives us the result and we can stop our search there. It is not possible that the shortest path exists from some other cell for which we haven’t reached the given node yet. If any such path was possible, we would have already explored it.

C++ implementation –

Download   Run Code



Exercise: Extend the solution to print the paths as well.

Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

Notify of
Sort by:   newest | oldest | most voted
Oleg Abrazhaev



“Exercise: Extend the solution to print the paths as well.”
What is the answer?