Skip to content

Instantly share code, notes, and snippets.

@khanha2
Created June 3, 2022 09:43
Show Gist options
  • Save khanha2/e18a980bec15c7fe59e0d538f3cdb5e7 to your computer and use it in GitHub Desktop.
Save khanha2/e18a980bec15c7fe59e0d538f3cdb5e7 to your computer and use it in GitHub Desktop.
Depth first search algorithm with Elixir
defmodule DFS do
@moduledoc """
Depth first search algorithm
Example
vertices = %{
0 => [1, 3],
1 => [0, 2],
2 => [1, 3],
3 => [2]
}
DFS.perform(0, 3, vertices)
"Visited 3"
"Visited 2"
"Visited 1"
"Visited 0"
true
"""
@spec perform(integer(), integer(), map()) :: boolean()
def perform(source, destination, vertices) do
recursive(source, destination, vertices)
end
defp recursive(vertex, destination, vertices, visited \\ MapSet.new()) do
result =
if vertex == destination do
true
else
visited = MapSet.put(visited, vertex)
adjacency_vertices = Enum.filter(vertices[vertex], &(not MapSet.member?(visited, &1)))
Enum.reduce_while(adjacency_vertices, false, fn adjacency, _acc ->
result = recursive(adjacency, destination, vertices, visited)
if result do
{:halt, true}
else
{:cont, false}
end
end)
end
IO.inspect("Visited #{vertex}")
result
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment