Search⌘ K
AI Features

Challenge: Implement Breadth-First Graph Traversal

Implement breadth-first graph traversal

Problem statement

You have to implement the breadth-first traversal in Python.

To solve this problem, the previously implemented Graph class is already prepended.

Input

A graph represented as an adjacency list and a starting vertex

Output

A string containing the vertices of the graph listed in the correct order of traversal

Sample input

Graph:

Vertex Edges
0 2, 1
1 4, 3
2 None
3 None
4 None

Source: 0

Sample output

result = "02143" 
or
result = "01234"

Traversal strategy: print the right child first and then, the left child.

Coding exercise

First, take a close look at this problem and design a step-by-step algorithm before jumping to the implementation. This problem is designed for your practice, so try to solve it on your own first. If you get stuck, you can always refer to the solution provided in the solution section. Good luck!

bfs
graph.py
def bfs(graph, source):
"""
Function to print a BFS of graph
:param graph: The graph
:param source: starting vertex
:return:
"""
# Write your code here!
pass