Skip to content

Instantly share code, notes, and snippets.

@khanha2
Created June 3, 2022 10:13
Show Gist options
  • Save khanha2/14ef69883a0520e67fbbfd0d4cc08cbc to your computer and use it in GitHub Desktop.
Save khanha2/14ef69883a0520e67fbbfd0d4cc08cbc to your computer and use it in GitHub Desktop.
Find Hamiltonian cycle algorithm with Elixir
defmodule HamiltonianCycle do
@moduledoc """
Find Hamiltonian cycle algorithm
Example
vertices = %{
0 => [1, 2],
1 => [0, 2, 3],
2 => [0, 1, 4],
3 => [1, 4],
4 => [2, 3]
}
HamiltonianCycle.perform(vertices)
"Vertex 3"
"Vertex 4"
"Vertex 2"
"Vertex 1"
"Vertex 0"
true
"""
def perform(vertices) do
recursive(0, vertices)
end
defp recursive(vertex, vertices, visited \\ MapSet.new()) do
adjacency_vertices = vertices[vertex]
total_vertices = Map.keys(vertices)
has_hamiltonian_cycle =
MapSet.size(visited) == length(total_vertices) - 1 and adjacency_vertices != []
result =
if has_hamiltonian_cycle do
true
else
visited = MapSet.put(visited, vertex)
adjacency_vertices
|> Enum.filter(&(not MapSet.member?(visited, &1)))
|> Enum.reduce_while(false, fn adjacency, _acc ->
result = recursive(adjacency, vertices, visited)
if result do
{:halt, true}
else
{:cont, false}
end
end)
end
IO.inspect("Vertex #{vertex}")
result
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment