From 5a1f681234c45e380cbeb76bb81027acffeb791b Mon Sep 17 00:00:00 2001 From: Manish Raj <2200032955@kluniversity.in> Date: Tue, 22 Oct 2024 23:37:19 +0530 Subject: [PATCH] Optimize BreadthFirstSearch implementation (#5882) --- .../searches/BreadthFirstSearch.java | 52 +++++++++++++------ 1 file changed, 37 insertions(+), 15 deletions(-) diff --git a/src/main/java/com/thealgorithms/searches/BreadthFirstSearch.java b/src/main/java/com/thealgorithms/searches/BreadthFirstSearch.java index debab98c6..7ac9c7b01 100644 --- a/src/main/java/com/thealgorithms/searches/BreadthFirstSearch.java +++ b/src/main/java/com/thealgorithms/searches/BreadthFirstSearch.java @@ -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 Breadth-first search */ public class BreadthFirstSearch { - private final List visited = new ArrayList<>(); + private final Set visitedSet = new HashSet<>(); - public Optional> search(final Node 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> search(final Node 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> queue = new ArrayDeque<>(node.getChildren()); + Queue> queue = new ArrayDeque<>(root.getChildren()); while (!queue.isEmpty()) { final Node 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 { return Optional.empty(); } + /** + * Returns the list of nodes in the order they were visited. + * + * @return List containing the visited nodes + */ public List getVisited() { return visited; }