mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-07-18 18:14:34 +08:00
Some directories had a capital in their name [fixed]. Added a recursive factorial algorithm. (#763)
* Renaming directories * Adding a recursive factorial algorithm
This commit is contained in:
39
graphs/BFS.py
Normal file
39
graphs/BFS.py
Normal file
@ -0,0 +1,39 @@
|
||||
"""pseudo-code"""
|
||||
|
||||
"""
|
||||
BFS(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)
|
||||
|
||||
"""
|
||||
|
||||
import collections
|
||||
|
||||
|
||||
def bfs(graph, start):
|
||||
explored, queue = set(), [start] # collections.deque([start])
|
||||
explored.add(start)
|
||||
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
|
||||
|
||||
|
||||
G = {'A': ['B', 'C'],
|
||||
'B': ['A', 'D', 'E'],
|
||||
'C': ['A', 'F'],
|
||||
'D': ['B'],
|
||||
'E': ['B', 'F'],
|
||||
'F': ['C', 'E']}
|
||||
|
||||
print(bfs(G, 'A'))
|
Reference in New Issue
Block a user