-
Notifications
You must be signed in to change notification settings - Fork 0
/
DfsIterativeTraversal.java
42 lines (36 loc) · 1.1 KB
/
DfsIterativeTraversal.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package graph;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class DfsIterativeTraversal implements Traversal {
private Graph graph;
public DfsIterativeTraversal(Graph graph) {
this.graph = graph;
}
@Override
public List<Integer> traverse() {
List<Integer> result = new ArrayList<>();
boolean[] visited = new boolean[graph.getVerticesCount()];
for (int i = 0; i < graph.getVerticesCount(); i++) {
if (!visited[i]) {
dfsIterative(i, visited, result);
}
}
return result;
}
private void dfsIterative(int source, boolean[] visited, List<Integer> result) {
Stack<Integer> stack = new Stack<>();
stack.add(source);
visited[source] = true;
while (!stack.isEmpty()) {
int node = stack.pop();
result.add(node);
for (int adj : graph.adjacent(node)) {
if (!visited[adj]) {
visited[adj] = true;
stack.add(adj);
}
}
}
}
}