2019-02-11 09:52:14 +00:00
|
|
|
"""
|
2020-06-25 15:54:41 +00:00
|
|
|
https://en.wikipedia.org/wiki/Breadth-first_search
|
2019-07-10 20:00:30 +00:00
|
|
|
pseudo-code:
|
2020-06-25 15:54:41 +00:00
|
|
|
breadth_first_search(graph G, start vertex s):
|
2019-02-11 09:52:14 +00:00
|
|
|
// 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)
|
|
|
|
"""
|
|
|
|
|
2020-06-25 15:54:41 +00:00
|
|
|
from typing import Set, Dict
|
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
G = {
|
|
|
|
"A": ["B", "C"],
|
|
|
|
"B": ["A", "D", "E"],
|
|
|
|
"C": ["A", "F"],
|
|
|
|
"D": ["B"],
|
|
|
|
"E": ["B", "F"],
|
|
|
|
"F": ["C", "E"],
|
|
|
|
}
|
2019-02-11 09:52:14 +00:00
|
|
|
|
|
|
|
|
2020-06-25 15:54:41 +00:00
|
|
|
def breadth_first_search(graph: Dict, start: str) -> Set[str]:
|
2019-07-25 07:49:00 +00:00
|
|
|
"""
|
2020-06-25 15:54:41 +00:00
|
|
|
>>> ''.join(sorted(breadth_first_search(G, 'A')))
|
2019-07-25 07:49:00 +00:00
|
|
|
'ABCDEF'
|
|
|
|
"""
|
2020-06-25 15:54:41 +00:00
|
|
|
explored = {start}
|
|
|
|
queue = [start]
|
2019-02-11 09:52:14 +00:00
|
|
|
while queue:
|
|
|
|
v = queue.pop(0) # queue.popleft()
|
|
|
|
for w in graph[v]:
|
|
|
|
if w not in explored:
|
|
|
|
explored.add(w)
|
|
|
|
queue.append(w)
|
|
|
|
return explored
|
|
|
|
|
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
if __name__ == "__main__":
|
2020-06-25 15:54:41 +00:00
|
|
|
print(breadth_first_search(G, "A"))
|