|
| 1 | +packageSearches; |
| 2 | + |
| 3 | +importSearches.DepthFirstSearch.Node; |
| 4 | + |
| 5 | +importjava.util.ArrayList; |
| 6 | +importjava.util.List; |
| 7 | +importjava.util.Objects; |
| 8 | +importjava.util.Optional; |
| 9 | + |
| 10 | +/** |
| 11 | + * @author: caos321 |
| 12 | + * @date: 31 October 2021 (Sunday) |
| 13 | + */ |
| 14 | +publicclassBreadthFirstSearch { |
| 15 | + |
| 16 | +publicstaticOptional<Node>search(finalNodenode,finalStringname) { |
| 17 | +if (node.getName().equals(name)) { |
| 18 | +returnOptional.of(node); |
| 19 | + } |
| 20 | + |
| 21 | +List<Node>queue =newArrayList<>(node.getSubNodes()); |
| 22 | + |
| 23 | +while(!queue.isEmpty()) { |
| 24 | +finalNodecurrent =queue.get(0); |
| 25 | + |
| 26 | +if(current.getName().equals(name)) { |
| 27 | +returnOptional.of(current); |
| 28 | + } |
| 29 | + |
| 30 | +queue.addAll(current.getSubNodes()); |
| 31 | + |
| 32 | +queue.remove(0); |
| 33 | + } |
| 34 | + |
| 35 | +returnOptional.empty(); |
| 36 | + } |
| 37 | + |
| 38 | +publicstaticvoidassertThat(finalObjectactual,finalObjectexpected) { |
| 39 | +if (!Objects.equals(actual,expected)) { |
| 40 | +thrownewAssertionError(String.format("expected=%s but was actual=%s",expected,actual)); |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | +publicstaticvoidmain(finalString[]args) { |
| 45 | +finalNoderootNode =newNode("A",List.of( |
| 46 | +newNode("B",List.of(newNode("D"),newNode("F",List.of( |
| 47 | +newNode("H"),newNode("I") |
| 48 | + )))), |
| 49 | +newNode("C",List.of(newNode("G"))), |
| 50 | +newNode("E") |
| 51 | + )); |
| 52 | + |
| 53 | + { |
| 54 | +finalStringexpected ="I"; |
| 55 | + |
| 56 | +finalNoderesult =search(rootNode,expected) |
| 57 | + .orElseThrow(() ->newAssertionError("Node not found!")); |
| 58 | + |
| 59 | +assertThat(result.getName(),expected); |
| 60 | + } |
| 61 | + |
| 62 | + { |
| 63 | +finalStringexpected ="G"; |
| 64 | + |
| 65 | +finalNoderesult =search(rootNode,expected) |
| 66 | + .orElseThrow(() ->newAssertionError("Node not found!")); |
| 67 | + |
| 68 | +assertThat(result.getName(),expected); |
| 69 | + } |
| 70 | + |
| 71 | + { |
| 72 | +finalStringexpected ="E"; |
| 73 | + |
| 74 | +finalNoderesult =search(rootNode,expected) |
| 75 | + .orElseThrow(() ->newAssertionError("Node not found!")); |
| 76 | + |
| 77 | +assertThat(result.getName(),expected); |
| 78 | + } |
| 79 | + } |
| 80 | +} |