Skip to content

Commit ba6a3d6

Browse files
caos321xzerosiriak
authored
Add Breadth First Search (TheAlgorithms#2801)
Co-authored-by: xzero <[email protected]> Co-authored-by: Andrii Siriak <[email protected]>
1 parent 7f3eb1b commit ba6a3d6

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed

Searches/BreadthFirstSearch.java

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

0 commit comments

Comments
 (0)