Python/graphs/breadth_first_search_2.py
Casper Rysgaard e6cf13cc03
Update queue implementation (#5388)
* Update queue implementation

Popping the first element of a list takes O(n) time.
Using a cyclic queue takes O(1) time.

* Add queue changes from extra files

* Update indentation

* Add empty line between imports

* Fix lines

* Apply suggestions from code review

Co-authored-by: John Law <johnlaw.po@gmail.com>

Co-authored-by: John Law <johnlaw.po@gmail.com>
2021-10-30 19:06:25 +08:00

48 lines
1.1 KiB
Python

"""
https://en.wikipedia.org/wiki/Breadth-first_search
pseudo-code:
breadth_first_search(graph G, start vertex s):
// all nodes initially unexplored
mark s as explored
let Q = queue data structure, initialized with s
while Q is non-empty:
remove the first node of Q, call it v
for each edge(v, w): // for w in graph[v]
if w unexplored:
mark w as explored
add w to Q (at the end)
"""
from __future__ import annotations
from queue import Queue
G = {
"A": ["B", "C"],
"B": ["A", "D", "E"],
"C": ["A", "F"],
"D": ["B"],
"E": ["B", "F"],
"F": ["C", "E"],
}
def breadth_first_search(graph: dict, start: str) -> set[str]:
"""
>>> ''.join(sorted(breadth_first_search(G, 'A')))
'ABCDEF'
"""
explored = {start}
queue = Queue()
queue.put(start)
while not queue.empty():
v = queue.get()
for w in graph[v]:
if w not in explored:
explored.add(w)
queue.put(w)
return explored
if __name__ == "__main__":
print(breadth_first_search(G, "A"))