Skip to content

Commit a056d2e

Browse files
committed
Add doctests and type hints to Graph.bfs
1 parent ebb8472 commit a056d2e

File tree

1 file changed

+26
-1
lines changed

1 file changed

+26
-1
lines changed

graphs/directed_and_undirected_weighted_graph.py

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -430,7 +430,32 @@ def fill_graph_randomly(self, c=-1):
430430
if n != i:
431431
self.add_pair(i, n, 1)
432432

433-
def bfs(self, s=-2):
433+
def bfs(self, s=-2) -> list[int]:
434+
"""
435+
Performs breadth-first search starting from node s.
436+
If s is not given, starts from the first node in the graph
437+
438+
>>> g = Graph()
439+
>>> g.add_pair(1,2)
440+
>>> g.add_pair(1,3)
441+
>>> g.add_pair(2,4)
442+
>>> g.add_pair(3,5)
443+
>>> g.bfs(1)
444+
[1, 2, 3, 4, 5]
445+
>>> g.bfs(2)
446+
[2, 1, 4, 3, 5]
447+
>>> g.bfs(4) # leaf node test
448+
[4, 2, 1, 3, 5]
449+
>>> g.bfs(10) # nonexistent node
450+
Traceback (most recent call last):
451+
...
452+
KeyError: 10
453+
>>> g2 = Graph()
454+
>>> g2.add_pair(10,20)
455+
>>> g2.add_pair(20,30)
456+
>>> g2.bfs()
457+
[10, 20, 30]
458+
"""
434459
d = deque()
435460
visited = []
436461
if s == -2:

0 commit comments

Comments
 (0)