Problem
Given a graph, perform BFS. Start from vertex 0, visit the vertices in the exact order as they appear in the graph, and ensure all vertices are visited.
Examples
[[2, 3, 1], [0], [0, 4], [0], [2]]Output[0, 2, 3, 1, 4][[1, 2], [0, 2], [0, 1, 3, 4], [2], [2]]Output[0, 1, 2, 3, 4]
Constraints
Expected Complexities
Time Complexity:
Auxiliary Space:
Solution
Python
from collections import deque
def bfs(adj):
visited = [False] * len(adj)
result = []
for i in range(len(adj)):
if not visited[i]:
queue = deque()
queue.append(i)
visited[i] = True
while queue:
current = queue.popleft()
result.append(current)
for neighbor in adj[current]:
if not visited[neighbor]:
queue.append(neighbor)
visited[neighbor] = True
return result
print(bfs([[2, 3, 1], [0], [0, 4], [0], [2]]))
print(bfs([[1, 2], [0, 2], [0, 1, 3, 4], [2], [2]]))