Optimize BreadthFirstSearch implementation (#5882)

This commit is contained in:
Manish Raj
2024-10-22 23:37:19 +05:30
committed by GitHub
parent 0bb22fbc7d
commit 5a1f681234

View File

@ -3,37 +3,54 @@ package com.thealgorithms.searches;
import com.thealgorithms.datastructures.Node;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Queue;
import java.util.Set;
/**
* @author: caos321
* @date: 31 October 2021 (Sunday)
* @wiki: https://en.wikipedia.org/wiki/Breadth-first_search
* Breadth-First Search implementation for tree/graph traversal.
* @author caos321
* @co-author @manishraj27
* @see <a href="https://en.wikipedia.org/wiki/Breadth-first_search">Breadth-first search</a>
*/
public class BreadthFirstSearch<T> {
private final List<T> visited = new ArrayList<>();
private final Set<T> visitedSet = new HashSet<>();
public Optional<Node<T>> search(final Node<T> node, final T value) {
if (node == null) {
/**
* Performs a breadth-first search to find a node with the given value.
*
* @param root The root node to start the search from
* @param value The value to search for
* @return Optional containing the found node, or empty if not found
*/
public Optional<Node<T>> search(final Node<T> root, final T value) {
if (root == null) {
return Optional.empty();
}
if (node.getValue().equals(value)) {
// add root node to visited
visited.add(value);
return Optional.of(node);
visited.add(root.getValue());
visitedSet.add(root.getValue());
if (root.getValue() == value) {
return Optional.of(root);
}
visited.add(node.getValue());
Queue<Node<T>> queue = new ArrayDeque<>(node.getChildren());
Queue<Node<T>> queue = new ArrayDeque<>(root.getChildren());
while (!queue.isEmpty()) {
final Node<T> current = queue.poll();
visited.add(current.getValue());
T currentValue = current.getValue();
if (current.getValue().equals(value)) {
if (visitedSet.contains(currentValue)) {
continue;
}
visited.add(currentValue);
visitedSet.add(currentValue);
if (currentValue == value || (value != null && value.equals(currentValue))) {
return Optional.of(current);
}
@ -43,6 +60,11 @@ public class BreadthFirstSearch<T> {
return Optional.empty();
}
/**
* Returns the list of nodes in the order they were visited.
*
* @return List containing the visited nodes
*/
public List<T> getVisited() {
return visited;
}