You are on page 1of 3

CSE316 - Artificial intelligence lab

Fall-2021
Lab Assignment

Question:
Find the shortest distance (minimum number of steps) taken by a knight to reach a given
destination from a given source on a chessboard.
For example,
Input:
N=8 #(8 × 8 board)
Source = (7, 0) #(row,column)
Destination = (0, 7) #(row,column)
Output:
Minimum number of steps required is 6
The knight’s movement is illustrated in the following figure:
Procedure:
The idea is to use Breadth–first search (BFS) to find the shortest path. Use the following
steps:
1. Create an empty queue and push the source cell having a distance of 0 from the source
(itself).
2. Loop till queue is empty:
a. Pop the next unvisited node.
b. If the popped node is the destination node, return its distance.
c. Otherwise, we mark the current node as visited. For each of eight possible
movements for a knight, push each valid movement (row and column value inside
the chessboard limit) with +1 distance
3. Print the distance value as output
A knight can move in eight possible directions from a given cell, as illustrated in the
following 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 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) a knight 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)

N.B.: We have to ensure these locations are valid that means they are inside our chessboard.

Submission instructions:
1. Ready the following file.
193-15-XXXXX-lab-assignment.py
2. Submit the file in the BLC activity.

You might also like