mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-01-31 06:33:44 +00:00
Added BFS and DFS (graph algorithms) (#408)
* feat: Add Breadth First Search (graph algorithm) * feat: Add Depth First Search (graph algorithm)
This commit is contained in:
parent
42d42c3136
commit
1cbbd5fe1a
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'))
|
36
Graphs/DFS.py
Normal file
36
Graphs/DFS.py
Normal file
|
@ -0,0 +1,36 @@
|
|||
"""pseudo-code"""
|
||||
|
||||
"""
|
||||
DFS(graph G, start vertex s):
|
||||
// all nodes initially unexplored
|
||||
mark s as explored
|
||||
for every edge (s, v):
|
||||
if v unexplored:
|
||||
DFS(G, v)
|
||||
"""
|
||||
|
||||
|
||||
def dfs(graph, start):
|
||||
"""The DFS function simply calls itself recursively for every unvisited child of its argument. We can emulate that
|
||||
behaviour precisely using a stack of iterators. Instead of recursively calling with a node, we'll push an iterator
|
||||
to the node's children onto the iterator stack. When the iterator at the top of the stack terminates, we'll pop
|
||||
it off the stack."""
|
||||
explored, stack = set(), [start]
|
||||
explored.add(start)
|
||||
while stack:
|
||||
v = stack.pop() # the only difference from BFS is to pop last element here instead of first one
|
||||
for w in graph[v]:
|
||||
if w not in explored:
|
||||
explored.add(w)
|
||||
stack.append(w)
|
||||
return explored
|
||||
|
||||
|
||||
G = {'A': ['B', 'C'],
|
||||
'B': ['A', 'D', 'E'],
|
||||
'C': ['A', 'F'],
|
||||
'D': ['B'],
|
||||
'E': ['B', 'F'],
|
||||
'F': ['C', 'E']}
|
||||
|
||||
print(dfs(G, 'A'))
|
Loading…
Reference in New Issue
Block a user