-
Notifications
You must be signed in to change notification settings - Fork 17
/
bfs.ex
45 lines (36 loc) · 1009 Bytes
/
bfs.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
defmodule Bfs do
@moduledoc """
Breadth First Search
"""
@type t :: Keyword.t
@type n :: non_neg_integer
@doc """
Visit all nodes in breadth first order and return a list of the nodes in the
order they were visited.
## Examples
iex> Bfs.visit(1, [{1,[2,3]}, {2,[1]}, {3,[1]}])
[1,2,3]
"""
@spec visit(n, t) :: t
def visit(start, nodes) do
visit(start, nodes, [])
end
defp visit(node, nodes, visited) do
visit_frontier([node], nodes, visited)
end
defp visit_frontier([]=_, _, visited) do
visited
end
defp visit_frontier([_|_]=frontier, nodes, visited) do
v = visited ++ frontier
x = Enum.filter(frontier_adj(frontier, nodes), fn(n) ->
!Enum.member?(visited, n)
end)
visit_frontier(x, nodes, v)
end
defp frontier_adj(frontier, nodes) do
Enum.reduce(frontier, [], fn(n, acc) ->
acc ++ nodes[n]
end)
end
end