Shortest Path Algorithm (Part 1)
Drawing an empty board to visualize the execution of shortest path algorithms.
This is the first part of a study on how shortest path algorithms work. This study is divided into three parts.
- 1) Draw an empty board
- 2) Add obstacles randomly
- 3) Implement the shortest path algorithm
# 1 - Dependencies
Before we start writing code, we need to install the python library Pillow.
pip install Pillow
# 2 - Imports
To draw the board, we need to import
ImageDraw classes from the Pillow library.
from PIL import Image, ImageDraw
*PIL is short for Python Image Library
# 3 - Classes
Now that we have our dependencies installed, let’s start defining the Node class.
The Node class will hold each position of the board.
Inside the draw method, we use the ImageDraw class to create the image of the node.
The most important part is the first parameter of the rectangle method. This parameter is responsible for the positions of the pixels that the class will use to draw our node.
The shape is an array with two positions. In the first position, we define where is the top/left edge of the rectangle and in the second, the bottom/right edge.
With these definitions, the method will draw:
- One vertical line from the left/top edge to the relative left/bottom edge;
- One vertical line from the right/bottom edge to the relative right/top edge;
- One horizontal line from the left/top edge to the relative right/top edge;
- One horizontal line from the right/bottom edge to the relative left/bottom edge.
In the end, we have a rectangle.
Now we need to create the Board class, to hold the matrix of Nodes, and draw the final image.
# 4 - Drawing
With the classes defined, now everything we need to do is create an instance of the Board class with the number of rows and cols the board has, then, just call the methods create and draw.
This is it! See you in the next part!