Skip to content

Commit a191f89

Browse files
Fix Non Recursive Depth First Search (TheAlgorithms#2207)
* Fix Non Recursive Depth First Search * Unindent docstring * Reindent docstring by 1 space Co-authored-by: Christian Clauss <[email protected]> Co-authored-by: Christian Clauss <[email protected]>
1 parent 1b3fec3 commit a191f89

File tree

1 file changed

+12
-21
lines changed

1 file changed

+12
-21
lines changed

graphs/depth_first_search.py

+12-21
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,12 @@
1-
"""The DFS function simply calls itself recursively for every unvisited child of
2-
its argument. We can emulate that behaviour precisely using a stack of iterators.
3-
Instead of recursively calling with a node, we'll push an iterator to the node's
4-
children onto the iterator stack. When the iterator at the top of the stack
5-
terminates, we'll pop it off the stack.
6-
7-
Pseudocode:
8-
all nodes initially unexplored
9-
mark s as explored
10-
for every edge (s, v):
11-
if v unexplored:
12-
DFS(G, v)
13-
"""
14-
from typing import Dict, Set
1+
"""Non recursive implementation of a DFS algorithm."""
2+
3+
from typing import Set, Dict
154

165

176
def depth_first_search(graph: Dict, start: str) -> Set[int]:
187
"""Depth First Search on Graph
19-
208
:param graph: directed graph in dictionary format
21-
:param vertex: starting vectex as a string
9+
:param vertex: starting vertex as a string
2210
:returns: the trace of the search
2311
>>> G = { "A": ["B", "C", "D"], "B": ["A", "D", "E"],
2412
... "C": ["A", "F"], "D": ["B", "D"], "E": ["B", "F"],
@@ -31,13 +19,16 @@ def depth_first_search(graph: Dict, start: str) -> Set[int]:
3119
True
3220
"""
3321
explored, stack = set(start), [start]
22+
3423
while stack:
3524
v = stack.pop()
36-
# one difference from BFS is to pop last element here instead of first one
37-
for w in graph[v]:
38-
if w not in explored:
39-
explored.add(w)
40-
stack.append(w)
25+
explored.add(v)
26+
# Differences from BFS:
27+
# 1) pop last element instead of first one
28+
# 2) add adjacent elements to stack without exploring them
29+
for adj in reversed(graph[v]):
30+
if adj not in explored:
31+
stack.append(adj)
4132
return explored
4233

4334

0 commit comments

Comments
 (0)