Given two squares
The challenge can be mapped into a simple combinatorial problem by considering the graph where each node corresponds to a square in the chessboard and two nodes are adjacent if and only if there is a legal knight move connecting them. Once such a graph has been constructed, the minimum paths connecting the input squares can then be obtained by means of the standard Dijkstra's algorithm.
The code relies on the Python libraries numpy
, networkx
and matplotlib
. The package graphviz is also necessary to convert the output .dot file into an .ps image of the requested graph.
Four scripts are included in the project:
graph_setup.py
, with the functions necessary to build the graph and draw it;pathfinding.py
, implementing the main algorithm;visualization.py
, containing all the functions necessary to create the output images;main.py
to build the output files.
The chessboard is indexed with numbers
The program will accept inputs both in algebraic notation (e.g.
shortest_paths.dot
and the correspondingshortest_path.ps
containing the directed graph representing the minimum paths (you can choose to allow or disallow multiple arrows between the same nodes at runtime);knight_graph.png
, an image of the graph underlying the program;shortest_paths_chessboard.png
, an image of the directed paths over an annotated chessboard, together with information about the number of paths and their length (including the starting and ending squares).
You will find the output corresponding to the case
Simply run the main file in order to generate the aforementioned output images. For Docker users, a Dockerfile is included in the project. The following steps are required in order to build and run a docker container:
- Make sure Docker is installed and active on your machine (run
sudo docker run hello-world
to check everything is working as expected). - In the project folder, run the command
sudo docker build -t my_project_image
to build the container. The -t option tags the container with the specified stringmy_project_image
. - Run
sudo docker run -it my_project_image .
to launch the program. You will be prompted to enter the squares (as mentioned, both algebraic and numerical notations are fine): note that the -it flag is essential to interact with the program. - Run
sudo docker ps -a
to see the ID corresponding to the generated container. - Finally, copy the contents in the desired location with the syntax:
sudo docker cp container_id:/container/path /host/path
. Example: if the container ID is 028a78bc0f1a, the output .ps file can be copied locally withsudo docker cp 028a78bc0f1a:/app/shortest_paths.ps /host/path
.