Skip to content
17 changes: 8 additions & 9 deletions graphs/bfs.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
"""
"""https://en.wikipedia.org/wiki/Breadth-first_search
BFS.

pseudo-code:

BFS(graph G, start vertex s):
// all nodes initially unexplored
mark s as explored
Expand All @@ -13,9 +11,10 @@
if w unexplored:
mark w as explored
add w to Q (at the end)

"""

from typing import Set, Dict

G = {
"A": ["B", "C"],
"B": ["A", "D", "E"],
Expand All @@ -26,13 +25,13 @@
}


def bfs(graph, start):
def breadth_first_search(graph: Dict, start: str) -> Set[str]:
"""
>>> ''.join(sorted(bfs(G, 'A')))
>>> ''.join(sorted(breadth_first_search(G, 'A')))
'ABCDEF'
"""
explored, queue = set(), [start] # collections.deque([start])
explored.add(start)
explored = {start}
queue = [start]
while queue:
v = queue.pop(0) # queue.popleft()
for w in graph[v]:
Expand All @@ -43,4 +42,4 @@ def bfs(graph, start):


if __name__ == "__main__":
print(bfs(G, "A"))
print(breadth_first_search(G, "A"))