Skip to content

Add url and typing hint for BFS #2156

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

Merged
merged 13 commits into from
Jun 25, 2020
Merged
Changes from all commits
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
19 changes: 9 additions & 10 deletions graphs/bfs.py → graphs/breadth_first_search_2.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
"""
BFS.

https://en.wikipedia.org/wiki/Breadth-first_search
pseudo-code:

BFS(graph G, start vertex s):
breadth_first_search(graph G, start vertex s):
// all nodes initially unexplored
mark s as explored
let Q = queue data structure, initialized with s
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"))