Breadth-First Search (BFS)
MEDIUMtime O(V + E)
space O(V)
Visited[1]
1
2
3
4
5
Queue
Initialize queue with start node 1 and mark it as visited.
Pseudocode
Pseudocode
1function bfs(graph, start):
2 queue = [start]
3 visited = {start}
4 while queue is not empty:
5 node = queue.shift()
6 for neighbor in graph[node]:
7 if neighbor not in visited:
8 visited.add(neighbor)
9 queue.push(neighbor)