Skip to content

Commit 5a1f681

Browse files
authored
Optimize BreadthFirstSearch implementation (#5882)
1 parent 0bb22fb commit 5a1f681

File tree

1 file changed

+37
-15
lines changed

1 file changed

+37
-15
lines changed

src/main/java/com/thealgorithms/searches/BreadthFirstSearch.java

Lines changed: 37 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3,37 +3,54 @@
33
import com.thealgorithms.datastructures.Node;
44
import java.util.ArrayDeque;
55
import java.util.ArrayList;
6+
import java.util.HashSet;
67
import java.util.List;
78
import java.util.Optional;
89
import java.util.Queue;
10+
import java.util.Set;
911

1012
/**
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>
1417
*/
1518
public class BreadthFirstSearch<T> {
16-
1719
private final List<T> visited = new ArrayList<>();
20+
private final Set<T> visitedSet = new HashSet<>();
1821

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) {
2131
return Optional.empty();
2232
}
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());
2933

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+
}
3140

41+
Queue<Node<T>> queue = new ArrayDeque<>(root.getChildren());
3242
while (!queue.isEmpty()) {
3343
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);
3552

36-
if (current.getValue().equals(value)) {
53+
if (currentValue == value || (value != null && value.equals(currentValue))) {
3754
return Optional.of(current);
3855
}
3956

@@ -43,6 +60,11 @@ public Optional<Node<T>> search(final Node<T> node, final T value) {
4360
return Optional.empty();
4461
}
4562

63+
/**
64+
* Returns the list of nodes in the order they were visited.
65+
*
66+
* @return List containing the visited nodes
67+
*/
4668
public List<T> getVisited() {
4769
return visited;
4870
}

0 commit comments

Comments
 (0)