From e5552e5af9667a246459c2b5e174660b1a5981cc Mon Sep 17 00:00:00 2001 From: Guo Date: Sun, 2 Jun 2019 23:10:01 +0800 Subject: [PATCH 1/2] Update DFS.py --- graphs/DFS.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/graphs/DFS.py b/graphs/DFS.py index d3c34fabb7b3..72be0e451d48 100644 --- a/graphs/DFS.py +++ b/graphs/DFS.py @@ -18,10 +18,13 @@ 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 not in explored: + explored.add(v) + for w in graph[v]: if w not in explored: - explored.add(w) stack.append(w) return explored From 138e09eb22a8bb75b3460d2220e0e14aef4b49b0 Mon Sep 17 00:00:00 2001 From: Guo Date: Sun, 2 Jun 2019 23:15:54 +0800 Subject: [PATCH 2/2] Update DFS.py --- graphs/DFS.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/graphs/DFS.py b/graphs/DFS.py index 72be0e451d48..c9843ca25382 100644 --- a/graphs/DFS.py +++ b/graphs/DFS.py @@ -20,8 +20,10 @@ def dfs(graph, start): while stack: v = stack.pop() # one difference from BFS is to pop last element here instead of first one - if v not in explored: - explored.add(v) + if v in explored: + continue + + explored.add(v) for w in graph[v]: if w not in explored: