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

Commitba6a3d6

Browse files
caos321xzerosiriak
authored
Add Breadth First Search (TheAlgorithms#2801)
Co-authored-by: xzero <andrejmezler@yahoo.de>Co-authored-by: Andrii Siriak <siryaka@gmail.com>
1 parent7f3eb1b commitba6a3d6

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed

‎Searches/BreadthFirstSearch.java

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

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp