Chess knight shortest path problem (Swift)

Resolving a chess knight shortest path problem with BFS (Breadth-first search) algorithm in Swift.

In order to understand this solution you need to know:

  1. Algorithms
  2. Queue
  3. Graph
  4. Breadth-First Search
Problem:

A chessboard is composed of 8×8 squares. In a chess game, knight is a piece that is allowed to move two squares horizontally and one square vertically or one square horizontally and two squares vertically.

Find a minimum number of steps required to reach destination square from the source square. Source and destination square origins are provided below as input values.

Input:

Source = (0,0)
Destination = (7,0)

Output:

Minimum number of steps required is 5.

Solution:
  1. In this case, chessboard is a graph where each square is a node or a vertex and each knight move is an edge or a link.  Create a matrix which represents all possible knight’s moves.
  2. For each square or a node create an adjacency list based on knight’s moves matrix.
  3. Transverse tree in a BFS fashion and find a shortest path to destination square or node or a vertex.
Xcode playground repo

Leave a Reply

Your email address will not be published. Required fields are marked *