Created
June 3, 2022 09:53
-
-
Save khanha2/a8eae498ed1797ad56d990c517b0ca9c to your computer and use it in GitHub Desktop.
Breadth first search algorithm with elixir
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
defmodule BFS do | |
@moduledoc """ | |
Breadth first search algorithm | |
Example | |
vertices = %{ | |
0 => [1, 3], | |
1 => [0, 2], | |
2 => [1, 3], | |
3 => [2] | |
} | |
BFS.perform(0, 3, vertices) | |
"Vertex 3" | |
"Vertex 1" | |
"Vertex 0" | |
true | |
""" | |
@spec perform(integer(), integer(), map()) :: boolean() | |
def perform(source, destination, vertices) do | |
visited = MapSet.new() | |
visited = MapSet.put(visited, source) | |
queue = [source] | |
recursive(destination, vertices, visited, queue) | |
end | |
defp recursive(destination, vertices, visited, queue) do | |
vertex = List.last(queue) | |
result = | |
cond do | |
is_nil(vertex) -> | |
false | |
vertex == destination -> | |
true | |
true -> | |
{_, queue} = List.pop_at(queue, -1) | |
adjacency_vertices = Enum.filter(vertices[vertex], &(not MapSet.member?(visited, &1))) | |
visited = | |
Enum.reduce(adjacency_vertices, visited, fn adjacency, acc -> | |
MapSet.put(acc, adjacency) | |
end) | |
queue = | |
Enum.reduce(adjacency_vertices, queue, fn adjacency, acc -> | |
[adjacency | acc] | |
end) | |
recursive(destination, vertices, visited, queue) | |
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