Skip to content

Instantly share code, notes, and snippets.

@lukegrecki
Last active November 23, 2017 00:00
Show Gist options
  • Save lukegrecki/135ac7eecaefe13987bccd5c792db1f2 to your computer and use it in GitHub Desktop.
Save lukegrecki/135ac7eecaefe13987bccd5c792db1f2 to your computer and use it in GitHub Desktop.
Finding a short hamiltonian path using the nearest neighbor algorithm
def find_short_hamiltonian_path(origin, nodes, costs, dependencies):
current_node = origin
visited_nodes = set([origin])
remaining_nodes = nodes - visited_nodes
path = [origin]
while len(remaining_nodes) > 0:
smallest_cost = float('inf')
for node in remaining_nodes:
if not is_valid_extension(visited_nodes, node, dependencies):
continue
if costs[current_node][node] < smallest_cost:
closest_node = node
smallest_cost = cost
path.append(closest_node)
remaining_nodes.remove(closest_node)
visited_nodes.add(closest_node)
current_node = closest_node
return path
def is_valid_extension(visited_nodes, new_node, dependencies):
if dependencies.get(new_node) and dependencies.get(new_node) not in visited_nodes:
return False
return True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment