Skip to content

Instantly share code, notes, and snippets.

@konami99
Created January 26, 2023 11:55
Show Gist options
  • Save konami99/2c1d6f5bf68bff1e71709c4c754ef066 to your computer and use it in GitHub Desktop.
Save konami99/2c1d6f5bf68bff1e71709c4c754ef066 to your computer and use it in GitHub Desktop.
def bfs_traverse(starting_vertex)
queue = Queue.new
visited_vertices = {}
visited_vertices[starting_vertex.value] = true
queue.enqueue(starting_vertex)
# While the queue is not empty:
while queue.read
# Remove the first vertex off the queue and make it the current vertex:
current_vertex = queue.dequeue
# Print the current vertex's value:
puts current_vertex.value
# Iterate over current vertex's adjacent vertices:
current_vertex.adjacent_vertices.each do |adjacent_vertex|
# If we have not yet visited the adjacent vertex:
if !visited_vertices[adjacent_vertex.value]
# Mark the adjacent vertex as visited:
visited_vertices[adjacent_vertex.value] = true
# Add the adjacent vertex to the queue:
queue.enqueue(adjacent_vertex)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment