Computing Hamiltonian Paths

Photo by Alina Grubnyak on Unsplash

Here is a little challenge for you. You are free do try solving it yourself, or write a Python program to do it. And here it is: Suppose we you have a dodecahedron and and ant is moving over the surface of the dodecahedron. But it is a very idiosyncratic ant. It wants to visit each and every vertex of the dodecahedron exactly once, and it only wants to walk along the edges and not over the facet surfaces. Can you find a path for the ant that satisfies these conditions?

The problem at hand is to find a Hamiltonian path on a dodecahedral graph. A Hamiltonian path is a path in an undirected or directed graph that visits each vertex exactly once. This is an interesting mathematical problem and can be related to various real-world scenarios. It might seem trivial at first, but solving it can be quite complex. The given Python code snippet uses the NetworkX library to create a dodecahedron graph and find a Hamiltonian path.


import networkx as nx
import matplotlib.pyplot as plt

# Create a dodecahedron graph
G = nx.dodecahedral_graph()

nx.draw(G, with_labels=True, node_size=500)
plt.gca().set_aspect("equal")

Now that we have represented the dodecahedron graph, the next step is to find a Hamiltonian path. A Hamiltonian path exists if there is a way to traverse the graph such that every vertex is visited exactly once. In the case of a dodecahedron, there are 20 vertices, and we can find the Hamiltonian path using the algorithms subpackage of NetworkX:


from networkx.algorithms import tournament

G = nx.DiGraph(G)
cycle = tournament.hamiltonian_path(G)

We first have to convert the graph to a DiGraph. This is a directed graph where each edge can be traversed in both directions. We need that because the hamiltonian_path function requires DiGraphs as argument. The output is:


cycle

[1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14, 17, 16, 19, 18]

The output is the sequence of node numbers in the Hamiltonian cycle. Let's check if that is really the path we want. The code snippet below visualizes the dodecahedral graph with the Hamiltonian path highlighted in red. This makes it easier to grasp the solution.


import networkx as nx
import matplotlib.pyplot as plt
from networkx.algorithms import tournament

cycle = tournament.hamiltonian_path(G)

# Draw the graph
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels=True, node_size=500)

# Draw the Hamiltonian path
nx.draw_networkx_edges(
    G, pos, 
    edgelist=list(zip(cycle, cycle[1:] + cycle[:1])), 
    edge_color="r", width=2
)

plt.gca().set_aspect("equal")
plt.show()

In conclusion, with a bit of creative problem framing and leveraging powerful mathematical algorithms through Python libraries, we have easily devised a path for our quirky ant.