Skip to content

Add to doctests #12790

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Add doctests and type hints to Graph.bfs
  • Loading branch information
tioBlachi committed Jun 9, 2025
commit a056d2e75b856047d035c9a63bbfae8dd2b0ff00
27 changes: 26 additions & 1 deletion graphs/directed_and_undirected_weighted_graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -430,7 +430,32 @@ def fill_graph_randomly(self, c=-1):
if n != i:
self.add_pair(i, n, 1)

def bfs(self, s=-2):
def bfs(self, s=-2) -> list[int]:
"""
Performs breadth-first search starting from node s.
If s is not given, starts from the first node in the graph

>>> g = Graph()
>>> g.add_pair(1,2)
>>> g.add_pair(1,3)
>>> g.add_pair(2,4)
>>> g.add_pair(3,5)
>>> g.bfs(1)
[1, 2, 3, 4, 5]
>>> g.bfs(2)
[2, 1, 4, 3, 5]
>>> g.bfs(4) # leaf node test
[4, 2, 1, 3, 5]
>>> g.bfs(10) # nonexistent node
Traceback (most recent call last):
...
KeyError: 10
>>> g2 = Graph()
>>> g2.add_pair(10,20)
>>> g2.add_pair(20,30)
>>> g2.bfs()
[10, 20, 30]
"""
d = deque()
visited = []
if s == -2:
Expand Down