diff --git a/src/graph/dfs.jl b/src/graph/dfs.jl index 18a4e175..3c9be87a 100644 --- a/src/graph/dfs.jl +++ b/src/graph/dfs.jl @@ -23,7 +23,13 @@ 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) @@ -31,6 +37,7 @@ 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) @@ -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]) @@ -49,6 +56,5 @@ function dfs(graph::Vector{Vector{Int}}, source::Int = 1) end end end - - return print("\n") + return result end diff --git a/test/graph.jl b/test/graph.jl index 09478f7e..4b4205a2 100644 --- a/test/graph.jl +++ b/test/graph.jl @@ -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