Skip to content

Commit b9a95d3

Browse files
authored
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.
1 parent 2bc5576 commit b9a95d3

1 file changed

Lines changed: 7 additions & 5 deletions

File tree

  • algorithms-searching/src/main/java/com/baeldung/algorithms/dfs

algorithms-searching/src/main/java/com/baeldung/algorithms/dfs/Graph.java

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -29,11 +29,13 @@ public void dfsWithoutRecursion(int start) {
2929
stack.push(start);
3030
while (!stack.isEmpty()) {
3131
int current = stack.pop();
32-
isVisited[current] = true;
33-
visit(current);
34-
for (int dest : adjVertices.get(current)) {
35-
if (!isVisited[dest])
36-
stack.push(dest);
32+
if(!isVisited[current]){
33+
isVisited[current] = true;
34+
visit(current);
35+
for (int dest : adjVertices.get(current)) {
36+
if (!isVisited[dest])
37+
stack.push(dest);
38+
}
3739
}
3840
}
3941
}

0 commit comments

Comments
 (0)