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.
This commit is contained in:
Ömer
2021-06-05 23:04:19 +03:00
committed by GitHub
parent 2bc5576f2b
commit b9a95d37e5

View File

@@ -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);
}
}
}
}