Skip to content

Commit

Permalink
refactor: make dfs return vector (#201)
Browse files Browse the repository at this point in the history
  • Loading branch information
vil02 authored Oct 22, 2023
1 parent 7d41efe commit 77864da
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
14 changes: 10 additions & 4 deletions src/graph/dfs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,21 @@ dfs(graph, 6)
# output
6 5 2 4 3 1
6-element Vector{Int64}:
6
5
2
4
3
1
```
Contributed by: [Yannick Brenning](https://github.com/ybrenning)
"""
function dfs(graph::Vector{Vector{Int}}, source::Int = 1)
# Use a boolean "visited" array to avoid processing a vertex more than once
visited = [false for _ in 1:length(graph)]
result = Vector{Int}()

stack = Stack{Int}()
push!(stack, source)
Expand All @@ -39,7 +46,7 @@ function dfs(graph::Vector{Vector{Int}}, source::Int = 1)

while length(stack) > 0
curr_v = pop!(stack)
print(curr_v, " ")
push!(result, curr_v)

# Add every unvisited target to the top of the stack
for i in 1:length(graph[curr_v])
Expand All @@ -49,6 +56,5 @@ function dfs(graph::Vector{Vector{Int}}, source::Int = 1)
end
end
end

return print("\n")
return result
end
14 changes: 14 additions & 0 deletions test/graph.jl
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,18 @@ using TheAlgorithms.Graph
@test bfs(graph, 4) == [4, 1, 2, 5, 3, 6]
@test bfs(graph) == [1, 2, 3, 6, 4, 5]
end

@testset "dfs" begin
graph = [
[2, 3, 6],
[3, 4],
[4],
[1, 2, 5],
[2],
[1, 5]
]

@test dfs(graph, 6) == [6, 5, 2, 4, 3, 1]
@test dfs(graph) == [1, 6, 5, 3, 4, 2]
end
end

0 comments on commit 77864da

Please sign in to comment.