2019-02-11 09:52:14 +00:00
|
|
|
"""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]
|
|
|
|
while stack:
|
2019-10-05 05:14:13 +00:00
|
|
|
v = (
|
|
|
|
stack.pop()
|
|
|
|
) # one difference from BFS is to pop last element here instead of first one
|
|
|
|
|
2019-06-04 08:34:28 +00:00
|
|
|
if v in explored:
|
|
|
|
continue
|
|
|
|
|
|
|
|
explored.add(v)
|
|
|
|
|
2019-02-11 09:52:14 +00:00
|
|
|
for w in graph[v]:
|
|
|
|
if w not in explored:
|
|
|
|
stack.append(w)
|
|
|
|
return explored
|
|
|
|
|
|
|
|
|
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
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
print(dfs(G, "A"))
|