34
loading...
This website collects cookies to deliver better user experience
Space complexlity | O(V) |
---|---|
Time complexity | O(V+E) |
Initialize a queue
Mark the node as visited by inserting it to a list
Insert the vertices into the queue
While len(queue) > 0:
# CODE FROM https://favtutor.com/blogs/breadth-first-search-python
graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}
visitedNodes = []
queue = []
def bfs(visitedList: list, graph: dict, node):
visitedList.append(node)
queue.append(node)
while queue:
m = queue.pop(0)
print (m, end = "\t")
for adjacent in graph[m]:
if adjacent not in visitedList:
visitedList.append(adjacent)
queue.append(adjacent)
bfs(visitedNodes, graph, '5') # 5 3 7 2 4 8
https://medium.com/edureka/breadth-first-search-algorithm-17d2c72f0eaa
https://www.quora.com/What-are-some-real-life-examples-of-Breadth-and-Depth-First-Search
https://www.hackerearth.com/practice/algorithms/graphs/breadth-first-search/tutorial/
https://www.tutorialspoint.com/data_structures_algorithms/breadth_first_traversal.htm