Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitb05b4d0

Browse files
caos321xzero
and
xzero
authored
Add DepthFirstSearch with Java Streams (TheAlgorithms#2800)
Co-authored-by: xzero <andrejmezler@yahoo.de>
1 parent27c5237 commitb05b4d0

File tree

1 file changed

+90
-0
lines changed

1 file changed

+90
-0
lines changed

‎Searches/DepthFirstSearch.java

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
packageSearches;
2+
3+
importjava.util.ArrayList;
4+
importjava.util.List;
5+
importjava.util.Objects;
6+
importjava.util.Optional;
7+
8+
/**
9+
* @author: caos321
10+
* @date: 31 October 2021 (Sunday)
11+
*/
12+
publicclassDepthFirstSearch {
13+
staticclassNode {
14+
privatefinalStringname;
15+
privatefinalList<Node>subNodes;
16+
17+
publicNode(finalStringname) {
18+
this.name =name;
19+
this.subNodes =newArrayList<>();
20+
}
21+
22+
publicNode(finalStringname,finalList<Node>subNodes) {
23+
this.name =name;
24+
this.subNodes =subNodes;
25+
}
26+
27+
publicStringgetName() {
28+
returnname;
29+
}
30+
31+
publicList<Node>getSubNodes() {
32+
returnsubNodes;
33+
}
34+
}
35+
36+
publicstaticOptional<Node>search(finalNodenode,finalStringname) {
37+
if (node.getName().equals(name)) {
38+
returnOptional.of(node);
39+
}
40+
41+
returnnode.getSubNodes()
42+
.stream()
43+
.map(value ->search(value,name))
44+
.flatMap(Optional::stream)
45+
.findAny();
46+
}
47+
48+
publicstaticvoidassertThat(finalObjectactual,finalObjectexpected) {
49+
if (!Objects.equals(actual,expected)) {
50+
thrownewAssertionError(String.format("expected=%s but was actual=%s",expected,actual));
51+
}
52+
}
53+
54+
publicstaticvoidmain(finalString[]args) {
55+
finalNoderootNode =newNode("A",List.of(
56+
newNode("B",List.of(newNode("D"),newNode("F",List.of(
57+
newNode("H"),newNode("I")
58+
)))),
59+
newNode("C",List.of(newNode("G"))),
60+
newNode("E")
61+
));
62+
63+
{
64+
finalStringexpected ="I";
65+
66+
finalNoderesult =search(rootNode,expected)
67+
.orElseThrow(() ->newAssertionError("Node not found!"));
68+
69+
assertThat(result.getName(),expected);
70+
}
71+
72+
{
73+
finalStringexpected ="G";
74+
75+
finalNoderesult =search(rootNode,expected)
76+
.orElseThrow(() ->newAssertionError("Node not found!"));
77+
78+
assertThat(result.getName(),expected);
79+
}
80+
81+
{
82+
finalStringexpected ="E";
83+
84+
finalNoderesult =search(rootNode,expected)
85+
.orElseThrow(() ->newAssertionError("Node not found!"));
86+
87+
assertThat(result.getName(),expected);
88+
}
89+
}
90+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp