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

For example,

Input:
 
N = 8 (8 × 8 board)
Source = (7, 0)
Destination = (0, 7)
 
Output: Minimum number of steps required is 6

The knight’s movement is illustrated in the following figure:

Chess Knight Problem
 

Practice this problem

 
The idea is to use Breadth–first search (BFS) as it is the shortest path problem. Following is the complete algorithm:

  1. Create an empty queue and enqueue the source cell having a distance of 0 from the source (itself).
  2. Loop till queue is empty:
    1. Dequeue next unvisited node.
    2. If the popped node is the destination node, return its distance.
    3. Otherwise, we mark the current node as visited. For each of eight possible movements for a knight, enqueue each valid movement with +1 distance (minimum distance of a given node from the source is one more than the minimum distance of parent from source).

 
A knight can move in eight possible directions from a given cell, as illustrated in the following figure:

 
Knight Movements

 
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 the following 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 the shortest path as 1 are visited first, followed by their adjacent cells having the 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 destination cell’s first occurrence gives us the result, and we can stop our search there. The shortest path cannot exist from some other cell for which we haven’t reached the given node yet. If any such path were possible, we would have already explored it.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

The minimum number of steps required is 6

Java


Download  Run Code

Output:

The minimum number of steps required is 6

Python


Download  Run Code

Output:

The minimum number of steps required is 6

The time complexity of the proposed solution is O(M × N) and requires O(M × N) extra space, where M and N are dimensions of the matrix.

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