Section 9.12 Building the Knight’s Tour Graph
To represent the knight’s tour problem as a graph we will use the following two ideas: Each square on the chessboard can be represented as a node in the graph. Each legal move by the knight can be represented as an edge in the graph. Figure 9.12.1 illustrates the legal moves by a knight and the corresponding edges in a graph.
To build the full graph for an n-by-n board we can use the C++ function shown in Listing 9.12.2. The
knightGraph
function makes one pass over the entire board. At each square on the board the knightGraph
function calls a helper, genLegalMoves
, to create a list of legal moves for that position on the board. All legal moves are then converted into edges in the graph. Another helper function coordToNum
converts a location on the board in terms of a row and a column into a linear vertex number similar to the vertex numbers shown in Figure 9.12.1.The
genLegalMoves
function (Listing 9.12.3) takes the position of the knight on the board and generates each of the eight possible moves. The legalCoord
helper function (Listing 9.12.3) makes sure that a particular move that is generated is still on the board.
Figure 9.12.4 shows the complete graph of possible moves on an eight-by-eight board. There are exactly 336 edges in the graph. Notice that the vertices corresponding to the edges of the board have fewer connections (legal moves) than the vertices in the middle of the board. Once again we can see how sparse the graph is. If the graph was fully connected there would be 4,096 edges. Since there are only 336 edges, the adjacency matrix would be only 8.2 percent full.
The full implementation of this is shown in Listing 9.12.5. In the main function, we traverse using our previously created breadth-first search between two locations. In the next chapter, we will implement a different algorithm called a
depth first search (DFS)
to solve our knight’s tour problem.You have attempted of activities on this page.