Knight's tour: Difference between revisions

m
(Added 11l)
Line 5,227:
</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
 
'''Solution'''
<lang Mathematica>knightsTourMoves[start_] :=
knightsTourMoves[start_] :=
Module[{
vertexLabels = (# -> ToString@c[[Quotient[# - 1, 8] + 1]] <> ToString[Mod[# - 1, 8] + 1]) & /@ Range[64], knightsGraph,
Line 5,238 ⟶ 5,236:
hamiltonianCycle = ((FindHamiltonianCycle[knightsGraph] /. UndirectedEdge -> DirectedEdge) /. labels)[[1]];
end = Cases[hamiltonianCycle, (x_ \[DirectedEdge] start) :> x][[1]];
FindShortestPath[g, start, end]]</lang>
</lang>
 
'''Usage'''
<lang Mathematica>knightsTourMoves["d8"]
knightsTourMoves["d8"]
 
(* out *)
Line 5,265 ⟶ 5,261:
41 -> "f1", 42 -> "f2", 43 -> "f3", 44 -> "f4", 45 -> "f5", 46 -> "f6", 47 -> "f7", 48 -> "f8",
49 -> "g1", 50 -> "g2", 51 -> "g3", 52 -> "g4", 53 -> "g5", 54 -> "g6",55 -> "g7", 56 -> "g8",
57 -> "h1", 58 -> "h2", 59 -> "h3", 60 -> "h4", 61 -> "h5", 62 -> "h6", 63 -> "h7", 64 -> "h8"}</lang>
 
</lang>
 
'''knightsGraph''' creates a graph of the solution space.
<lang Mathematica>knightsGraph = KnightTourGraph[i, i, VertexLabels -> vertexLabels, ImagePadding -> 15];</lang>
<lang Mathematica>
knightsGraph = KnightTourGraph[i, i, VertexLabels -> vertexLabels, ImagePadding -> 15];
</lang>
[[File:KnightsTour-3.png]]
 
Find a Hamiltonian cycle (a path that visits each square exactly one time.)
 
<lang Mathematica>hamiltonianCycle = ((FindHamiltonianCycle[knightsGraph] /. UndirectedEdge -> DirectedEdge) /. labels)[[1]];</lang>
<lang Mathematica>
hamiltonianCycle = ((FindHamiltonianCycle[knightsGraph] /. UndirectedEdge -> DirectedEdge) /. labels)[[1]];
</lang>
 
Find the end square:
 
<lang Mathematica>end = Cases[hamiltonianCycle, (x_ \[DirectedEdge] start) :> x][[1]];</lang>
<lang Mathematica>
end = Cases[hamiltonianCycle, (x_ \[DirectedEdge] start) :> x][[1]];
</lang>
 
Find shortest path from the start square to the end square.
 
<lang Mathematica>FindShortestPath[g, start, end]]</lang>
FindShortestPath[g, start, end]]
</lang>
 
=={{header|Mathprog}}==
1,111

edits