Skip to content

Commit f9b8dbf

Browse files
ZJUGuoShuaipoyea
authored andcommitted
Correct the wrong iterative DFS implementation (TheAlgorithms#867)
* Update DFS.py * Update DFS.py
1 parent c2552cd commit f9b8dbf

File tree

1 file changed

+7
-2
lines changed

1 file changed

+7
-2
lines changed

graphs/DFS.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,15 @@ def dfs(graph, start):
1818
explored, stack = set(), [start]
1919
explored.add(start)
2020
while stack:
21-
v = stack.pop() # the only difference from BFS is to pop last element here instead of first one
21+
v = stack.pop() # one difference from BFS is to pop last element here instead of first one
22+
23+
if v in explored:
24+
continue
25+
26+
explored.add(v)
27+
2228
for w in graph[v]:
2329
if w not in explored:
24-
explored.add(w)
2530
stack.append(w)
2631
return explored
2732

0 commit comments

Comments
 (0)