-
Notifications
You must be signed in to change notification settings - Fork 17
/
dfs.ex
36 lines (29 loc) · 804 Bytes
/
dfs.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
defmodule Dfs do
@moduledoc """
Depth First Search
"""
@type t :: Keyword.t
@type n :: non_neg_integer
@doc """
Visit all nodes in depth first order and return a list of the nodes in the
order they were visited.
## Examples
iex> Dfs.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
Enum.reduce(nodes[node], visited ++ [node], fn(n, acc) ->
visit_recur(n, nodes, acc)
end)
end
defp visit_recur(node, nodes, visited) do
case Enum.member?(visited, node) do
true -> visited
false -> visit(node, nodes, visited)
end
end
end