3
3
import com .thealgorithms .datastructures .Node ;
4
4
import java .util .ArrayDeque ;
5
5
import java .util .ArrayList ;
6
+ import java .util .HashSet ;
6
7
import java .util .List ;
7
8
import java .util .Optional ;
8
9
import java .util .Queue ;
10
+ import java .util .Set ;
9
11
10
12
/**
11
- * @author: caos321
12
- * @date: 31 October 2021 (Sunday)
13
- * @wiki: https://en.wikipedia.org/wiki/Breadth-first_search
13
+ * Breadth-First Search implementation for tree/graph traversal.
14
+ * @author caos321
15
+ * @co-author @manishraj27
16
+ * @see <a href="https://en.wikipedia.org/wiki/Breadth-first_search">Breadth-first search</a>
14
17
*/
15
18
public class BreadthFirstSearch <T > {
16
-
17
19
private final List <T > visited = new ArrayList <>();
20
+ private final Set <T > visitedSet = new HashSet <>();
18
21
19
- public Optional <Node <T >> search (final Node <T > node , final T value ) {
20
- if (node == null ) {
22
+ /**
23
+ * Performs a breadth-first search to find a node with the given value.
24
+ *
25
+ * @param root The root node to start the search from
26
+ * @param value The value to search for
27
+ * @return Optional containing the found node, or empty if not found
28
+ */
29
+ public Optional <Node <T >> search (final Node <T > root , final T value ) {
30
+ if (root == null ) {
21
31
return Optional .empty ();
22
32
}
23
- if (node .getValue ().equals (value )) {
24
- // add root node to visited
25
- visited .add (value );
26
- return Optional .of (node );
27
- }
28
- visited .add (node .getValue ());
29
33
30
- Queue <Node <T >> queue = new ArrayDeque <>(node .getChildren ());
34
+ visited .add (root .getValue ());
35
+ visitedSet .add (root .getValue ());
36
+
37
+ if (root .getValue () == value ) {
38
+ return Optional .of (root );
39
+ }
31
40
41
+ Queue <Node <T >> queue = new ArrayDeque <>(root .getChildren ());
32
42
while (!queue .isEmpty ()) {
33
43
final Node <T > current = queue .poll ();
34
- visited .add (current .getValue ());
44
+ T currentValue = current .getValue ();
45
+
46
+ if (visitedSet .contains (currentValue )) {
47
+ continue ;
48
+ }
49
+
50
+ visited .add (currentValue );
51
+ visitedSet .add (currentValue );
35
52
36
- if (current . getValue () .equals (value )) {
53
+ if (currentValue == value || ( value != null && value .equals (currentValue ) )) {
37
54
return Optional .of (current );
38
55
}
39
56
@@ -43,6 +60,11 @@ public Optional<Node<T>> search(final Node<T> node, final T value) {
43
60
return Optional .empty ();
44
61
}
45
62
63
+ /**
64
+ * Returns the list of nodes in the order they were visited.
65
+ *
66
+ * @return List containing the visited nodes
67
+ */
46
68
public List <T > getVisited () {
47
69
return visited ;
48
70
}
0 commit comments