From f9b8dbf9db6c5b6cdd4ec9b5e35fbc1d9939a45e Mon Sep 17 00:00:00 2001 From: Guo Date: Tue, 4 Jun 2019 16:34:28 +0800 Subject: [PATCH] Correct the wrong iterative DFS implementation (#867) * Update DFS.py * Update DFS.py --- graphs/DFS.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/graphs/DFS.py b/graphs/DFS.py index d3c34fabb..c9843ca25 100644 --- a/graphs/DFS.py +++ b/graphs/DFS.py @@ -18,10 +18,15 @@ def dfs(graph, start): 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 + v = stack.pop() # one difference from BFS is to pop last element here instead of first one + + if v in explored: + continue + + explored.add(v) + for w in graph[v]: if w not in explored: - explored.add(w) stack.append(w) return explored