Last active
October 29, 2022 07:21
-
-
Save mikkelam/ab7966e7ab1c441f947b to your computer and use it in GitHub Desktop.
Finds a hamiltonian path using networkx graph library in Python with a backtrack solution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import networkx as nx | |
def hamilton(G): | |
F = [(G,[list(G.nodes())[0]])] | |
n = G.number_of_nodes() | |
while F: | |
graph,path = F.pop() | |
confs = [] | |
neighbors = (node for node in graph.neighbors(path[-1]) | |
if node != path[-1]) #exclude self loops | |
for neighbor in neighbors: | |
conf_p = path[:] | |
conf_p.append(neighbor) | |
conf_g = nx.Graph(graph) | |
conf_g.remove_node(path[-1]) | |
confs.append((conf_g,conf_p)) | |
for g,p in confs: | |
if len(p)==n: | |
return p | |
else: | |
F.append((g,p)) | |
return None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi @Quertsy I think (41,41) might be way too large to compute in reasonable time. The time complexity of this algorithm should be
O(N!)
in the worst case. I think you should be looking at other solvers that use heuristics if you're using such a large data set.