mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-01-31 06:33:44 +00:00
Add url and typing hint for BFS (#2156)
* Add typing for bfs * Add url for BFS * rename the function Co-authored-by: Christian Clauss <cclauss@me.com> * Update graphs/bfs.py Co-authored-by: Christian Clauss <cclauss@me.com> * Change the return value type of bfs * change the function name. change all instances of bfs() to breadth_first_search(). * change the function name in annotate * Add one more blank line. * Delete one blank line. * Delete one blank line. I've read the https://www.flake8rules.com/rules/W391.html, and still don't know how to do it. I've tried using 0 ,1,2 blank lines... * Update graphs/bfs.py Co-authored-by: Christian Clauss <cclauss@me.com> * Update graphs/bfs.py Co-authored-by: Christian Clauss <cclauss@me.com> * Rename bfs.py to breadth_first_search_2.py Co-authored-by: Christian Clauss <cclauss@me.com>
This commit is contained in:
parent
3d4172307f
commit
d2fa91b18e
|
@ -1,9 +1,7 @@
|
||||||
"""
|
"""
|
||||||
BFS.
|
https://en.wikipedia.org/wiki/Breadth-first_search
|
||||||
|
|
||||||
pseudo-code:
|
pseudo-code:
|
||||||
|
breadth_first_search(graph G, start vertex s):
|
||||||
BFS(graph G, start vertex s):
|
|
||||||
// all nodes initially unexplored
|
// all nodes initially unexplored
|
||||||
mark s as explored
|
mark s as explored
|
||||||
let Q = queue data structure, initialized with s
|
let Q = queue data structure, initialized with s
|
||||||
|
@ -13,9 +11,10 @@ while Q is non-empty:
|
||||||
if w unexplored:
|
if w unexplored:
|
||||||
mark w as explored
|
mark w as explored
|
||||||
add w to Q (at the end)
|
add w to Q (at the end)
|
||||||
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
from typing import Set, Dict
|
||||||
|
|
||||||
G = {
|
G = {
|
||||||
"A": ["B", "C"],
|
"A": ["B", "C"],
|
||||||
"B": ["A", "D", "E"],
|
"B": ["A", "D", "E"],
|
||||||
|
@ -26,13 +25,13 @@ G = {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
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'
|
'ABCDEF'
|
||||||
"""
|
"""
|
||||||
explored, queue = set(), [start] # collections.deque([start])
|
explored = {start}
|
||||||
explored.add(start)
|
queue = [start]
|
||||||
while queue:
|
while queue:
|
||||||
v = queue.pop(0) # queue.popleft()
|
v = queue.pop(0) # queue.popleft()
|
||||||
for w in graph[v]:
|
for w in graph[v]:
|
||||||
|
@ -43,4 +42,4 @@ def bfs(graph, start):
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
print(bfs(G, "A"))
|
print(breadth_first_search(G, "A"))
|
Loading…
Reference in New Issue
Block a user