Skip to content

Commit b05b4d0

Browse files
caos321xzero
and
xzero
authored
Add DepthFirstSearch with Java Streams (TheAlgorithms#2800)
Co-authored-by: xzero <[email protected]>
1 parent 27c5237 commit b05b4d0

File tree

1 file changed

+90
-0
lines changed

1 file changed

+90
-0
lines changed

Searches/DepthFirstSearch.java

+90
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
package Searches;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
import java.util.Objects;
6+
import java.util.Optional;
7+
8+
/**
9+
* @author: caos321
10+
* @date: 31 October 2021 (Sunday)
11+
*/
12+
public class DepthFirstSearch {
13+
static class Node {
14+
private final String name;
15+
private final List<Node> subNodes;
16+
17+
public Node(final String name) {
18+
this.name = name;
19+
this.subNodes = new ArrayList<>();
20+
}
21+
22+
public Node(final String name, final List<Node> subNodes) {
23+
this.name = name;
24+
this.subNodes = subNodes;
25+
}
26+
27+
public String getName() {
28+
return name;
29+
}
30+
31+
public List<Node> getSubNodes() {
32+
return subNodes;
33+
}
34+
}
35+
36+
public static Optional<Node> search(final Node node, final String name) {
37+
if (node.getName().equals(name)) {
38+
return Optional.of(node);
39+
}
40+
41+
return node.getSubNodes()
42+
.stream()
43+
.map(value -> search(value, name))
44+
.flatMap(Optional::stream)
45+
.findAny();
46+
}
47+
48+
public static void assertThat(final Object actual, final Object expected) {
49+
if (!Objects.equals(actual, expected)) {
50+
throw new AssertionError(String.format("expected=%s but was actual=%s", expected, actual));
51+
}
52+
}
53+
54+
public static void main(final String[] args) {
55+
final Node rootNode = new Node("A", List.of(
56+
new Node("B", List.of(new Node("D"), new Node("F", List.of(
57+
new Node("H"), new Node("I")
58+
)))),
59+
new Node("C", List.of(new Node("G"))),
60+
new Node("E")
61+
));
62+
63+
{
64+
final String expected = "I";
65+
66+
final Node result = search(rootNode, expected)
67+
.orElseThrow(() -> new AssertionError("Node not found!"));
68+
69+
assertThat(result.getName(), expected);
70+
}
71+
72+
{
73+
final String expected = "G";
74+
75+
final Node result = search(rootNode, expected)
76+
.orElseThrow(() -> new AssertionError("Node not found!"));
77+
78+
assertThat(result.getName(), expected);
79+
}
80+
81+
{
82+
final String expected = "E";
83+
84+
final Node result = search(rootNode, expected)
85+
.orElseThrow(() -> new AssertionError("Node not found!"));
86+
87+
assertThat(result.getName(), expected);
88+
}
89+
}
90+
}

0 commit comments

Comments
 (0)