In chess, the knight is a piece that moves in an \(L\)-shaped fashion: that is, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically.
The following snippet lets you click any two tiles on a chessboard and shows the shortest path a knight can take to go from one to the other.
How do we get the shortest path?
We model the problem in terms of graphs: each square in the chessboard will be a node, and we connect two nodes with an edge if a knight can move between the corresponding squares.
Now, we can use Dijkstra’s algorithm to find the shortest path in the graph.
That means that we are going to transverse the graph in a breath-first way, while keeping track of the visited nodes and the previous node in the shortest path.
Running this code will keep track of the previous node to each node along the shortest path, so we need to implement the following method to read the path.
And that’s it! A nice thing to notice is that no matter what two squares we choose, we can always move a knight from one to the other.
If you liked the snippet, you can check out the code on my Github.