Skip to content

Commit 987ca9a

Browse files
Fix Non Recursive Depth First Search
1 parent 19b713a commit 987ca9a

File tree

1 file changed

+8
-6
lines changed

1 file changed

+8
-6
lines changed

graphs/depth_first_search.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ def depth_first_search(graph: Dict, start: str) -> Set[int]:
1919
"""Depth First Search on Graph
2020
2121
:param graph: directed graph in dictionary format
22-
:param vertex: starting vectex as a string
22+
:param vertex: starting vertex as a string
2323
:returns: the trace of the search
2424
>>> G = { "A": ["B", "C", "D"], "B": ["A", "D", "E"],
2525
... "C": ["A", "F"], "D": ["B", "D"], "E": ["B", "F"],
@@ -32,13 +32,15 @@ def depth_first_search(graph: Dict, start: str) -> Set[int]:
3232
True
3333
"""
3434
explored, stack = set(start), [start]
35+
3536
while stack:
3637
v = stack.pop()
37-
# one difference from BFS is to pop last element here instead of first one
38-
for w in graph[v]:
39-
if w not in explored:
40-
explored.add(w)
41-
stack.append(w)
38+
explored.add(v)
39+
# Differences from BFS:
40+
# 1) pop last element instead of first one
41+
# 2) add adjacent elements to stack without exploring them
42+
for adj in reversed(graph[v]):
43+
if adj not in explored: stack.append(adj)
4244
return explored
4345

4446

0 commit comments

Comments
 (0)