Chess knight move in 8x8 chessboard

Following the suggestion of @BarakManos:

Step 1: Construct a graph where each square of the chess board is a vertex.

Step 2: Place an edge between vertices exactly when there is a single knight-move from one square to another.

Step 3: Dijkstra's algorithm is an algorithm to find the length of a path between two vertices (squares). It is very classical in graph theory, data structures, and algorithms.


There's actually few restrictions that are due to the edge of the board. One of these (or the only case) is moving from A1 to B2 for example. Normally it would take two moves to move one step diagonally, but here that solution would move you of board. Instead you would have to move to C2 or B3 first and then it's a move one step along file or row which is three steps.

Then it should be quite straight forward to just testing for solutions. The reason you don't get that many restrictions from the edges is that there will be similar solutions by symmetry that would avoid the restriction of the edges.

I wrote a program using the following algorithm:

  1. Create a array of squares
  2. Write zero in one array, then for each $j\in\mathbb N$:
  3. For each square with value $j$ put $j+1$ in all empty squares reachable by a knight jump. Repeat for successive $j$'s until the board is filled.

Well this is kind of similar to Dijkstra's algorithm (except in this case the distances are all one). My program confirmed that on a regular chess board the only case where the edges are a restriction is the mentioned case.


Dijkstra is overkill here.
Construct the graph as said in other answers, since the weight of edges are add one, one can find shortest path in a simple graph using Breadth First Search in O(V+E) instead of O(E + VlogV) as in Dijkstra.
If you want to find all of shortest paths from all cell to all others, you can use Floyd-Warshall algorithm since your vertexes in the graph are 64, this can be computed in O(n^3).
I should add that between Dijkstra, BFS and Floyd-Warshall , Floyd-Warshall is the easiest one to implement . and it is feasible to use it up to a 10*10 board.


In this video you can find out more about finding shortest path using BFS
And in this wiki you can learn about Floyd-Warshall algorithm.