Skip to content

Instantly share code, notes, and snippets.

@amankharwal

amankharwal/breadth_search.py Secret

Created Feb 17, 2021
Embed
What would you like to do?
def breadth_first(graph, root):
queue = Queue()
visited_nodes = list()
queue.enqueue(root)
visited_nodes.append(root)
current_node = root
while queue.size > 0:
current_node = queue.dequeue()
adj_nodes = graph[current_node]
remaining_elements = sorted(set(adj_nodes) - set(visited_nodes))
if len(remaining_elements) > 0:
for element in remaining_elements:
visited_nodes.append(element)
queue.enqueue(element)
return visited_nodes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment