Skip to content

Commit cb33e87

Browse files
committed
dfs improvement
1 parent f817de8 commit cb33e87

File tree

2 files changed

+12
-8
lines changed

2 files changed

+12
-8
lines changed

src/java/sequential/graph/dfs/IterativeDepthFirstTraversal.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,8 @@
1010
public class IterativeDepthFirstTraversal {
1111

1212
public static <T> Collection<T> dfs(Map<T, List<T>> graph, T root) {
13-
var searchStack = new ArrayDeque<T>();
1413
var explored = new LinkedHashSet<T>();
14+
var searchStack = new ArrayDeque<T>();
1515

1616
searchStack.add(root);
1717
while (!searchStack.isEmpty()) {

src/java/sequential/graph/dfs/RecursiveDepthFirstTraversal.java

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,22 +7,26 @@
77
import java.util.Set;
88

99

10-
class RecursiveDepthFirstTraversal {
10+
class RecursiveDepthFirstTraversal<T> {
1111

12-
public static <T> Collection<T> dfs(Map<T, List<T>> graph, T root) {
13-
var explored = new LinkedHashSet<T>();
12+
private Map<T, List<T>> graph;
13+
private Set<T> explored;
1414

15-
explore(root, graph, explored);
15+
public Collection<T> dfs(Map<T, List<T>> graph, T root) {
16+
this.graph = graph;
17+
explored = new LinkedHashSet<>();
18+
19+
explore(root);
1620

1721
return explored;
1822
}
1923

20-
private static <T> void explore(T node, Map<T, List<T>> graph, Set<T> explored) {
24+
private void explore(T node) {
2125
explored.add(node);
2226

2327
var successors = graph.getOrDefault(node, List.of());
2428
for (var succ : successors)
25-
if (!explored.contains(succ)) explore(node, graph, explored);
29+
if (!explored.contains(succ)) explore(succ);
2630
}
2731

2832

@@ -35,7 +39,7 @@ public static void main(String[] args) {
3539
);
3640

3741
System.out.println(
38-
dfs(graph, "you")
42+
new RecursiveDepthFirstTraversal().dfs(graph, "you")
3943
);
4044
}
4145
}

0 commit comments

Comments
 (0)