From 812057b43cad1b07aa2133898e608cd04b8048ab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=96mer?= <59844362+omertopuz@users.noreply.github.com> Date: Sat, 5 Jun 2021 23:04:19 +0300 Subject: [PATCH] Update Graph.java for dfsWithoutRecursion, when a node popped from the stack it should be checked that the current node is visited or not. Since stack has duplicated nodes, some nodes is visired doubly. --- .../main/java/com/baeldung/algorithms/dfs/Graph.java | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/algorithms-searching/src/main/java/com/baeldung/algorithms/dfs/Graph.java b/algorithms-searching/src/main/java/com/baeldung/algorithms/dfs/Graph.java index d2cc723cf9..4623dbb7a4 100644 --- a/algorithms-searching/src/main/java/com/baeldung/algorithms/dfs/Graph.java +++ b/algorithms-searching/src/main/java/com/baeldung/algorithms/dfs/Graph.java @@ -29,11 +29,13 @@ public class Graph { stack.push(start); while (!stack.isEmpty()) { int current = stack.pop(); - isVisited[current] = true; - visit(current); - for (int dest : adjVertices.get(current)) { - if (!isVisited[dest]) - stack.push(dest); + if(!isVisited[current]){ + isVisited[current] = true; + visit(current); + for (int dest : adjVertices.get(current)) { + if (!isVisited[dest]) + stack.push(dest); + } } } }