Skip to content

Commit

Permalink
refactor: make bfs return vector (#202)
Browse files Browse the repository at this point in the history
Co-authored-by: Soc Virnyl S. Estela <[email protected]>
  • Loading branch information
vil02 and uncomfyhalomacro authored Oct 22, 2023
1 parent 21e9422 commit 7d41efe
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
13 changes: 10 additions & 3 deletions src/graph/bfs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,21 @@ TheAlgorithms.Graph.bfs(graph, 4)
# output
4 1 2 5 3 6
6-element Vector{Int64}:
4
1
2
5
3
6
```
Contributed by: [Yannick Brenning](https://github.com/ybrenning)
"""
function bfs(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}()

queue = Queue{Int}()
enqueue!(queue, source)
Expand All @@ -39,7 +46,7 @@ function bfs(graph::Vector{Vector{Int}}, source::Int = 1)

while length(queue) > 0
curr_v = dequeue!(queue)
print(curr_v, " ")
push!(result, curr_v)

# Add every unvisited target to the end of the queue
for i in 1:length(graph[curr_v])
Expand All @@ -50,5 +57,5 @@ function bfs(graph::Vector{Vector{Int}}, source::Int = 1)
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 @@ -41,4 +41,18 @@ using TheAlgorithms.Graph

@test_throws ErrorException bellman_ford(negative_edge_cycle, 1)
end

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

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

0 comments on commit 7d41efe

Please sign in to comment.