From ba6a3d68567056eb3cb7e02e89dcbbdfde6a71e8 Mon Sep 17 00:00:00 2001 From: caos321 <36530240+caos321@users.noreply.github.com> Date: Mon, 8 Nov 2021 19:25:18 +0100 Subject: [PATCH] Add Breadth First Search (#2801) Co-authored-by: xzero Co-authored-by: Andrii Siriak --- Searches/BreadthFirstSearch.java | 80 ++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 Searches/BreadthFirstSearch.java diff --git a/Searches/BreadthFirstSearch.java b/Searches/BreadthFirstSearch.java new file mode 100644 index 000000000..c0abf82ba --- /dev/null +++ b/Searches/BreadthFirstSearch.java @@ -0,0 +1,80 @@ +package Searches; + +import Searches.DepthFirstSearch.Node; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.Optional; + +/** + * @author: caos321 + * @date: 31 October 2021 (Sunday) + */ +public class BreadthFirstSearch { + + public static Optional search(final Node node, final String name) { + if (node.getName().equals(name)) { + return Optional.of(node); + } + + List queue = new ArrayList<>(node.getSubNodes()); + + while(!queue.isEmpty()) { + final Node current = queue.get(0); + + if(current.getName().equals(name)) { + return Optional.of(current); + } + + queue.addAll(current.getSubNodes()); + + queue.remove(0); + } + + return Optional.empty(); + } + + public static void assertThat(final Object actual, final Object expected) { + if (!Objects.equals(actual, expected)) { + throw new AssertionError(String.format("expected=%s but was actual=%s", expected, actual)); + } + } + + public static void main(final String[] args) { + final Node rootNode = new Node("A", List.of( + new Node("B", List.of(new Node("D"), new Node("F", List.of( + new Node("H"), new Node("I") + )))), + new Node("C", List.of(new Node("G"))), + new Node("E") + )); + + { + final String expected = "I"; + + final Node result = search(rootNode, expected) + .orElseThrow(() -> new AssertionError("Node not found!")); + + assertThat(result.getName(), expected); + } + + { + final String expected = "G"; + + final Node result = search(rootNode, expected) + .orElseThrow(() -> new AssertionError("Node not found!")); + + assertThat(result.getName(), expected); + } + + { + final String expected = "E"; + + final Node result = search(rootNode, expected) + .orElseThrow(() -> new AssertionError("Node not found!")); + + assertThat(result.getName(), expected); + } + } +}