|
| 1 | +packageSearches; |
| 2 | + |
| 3 | +importjava.util.ArrayList; |
| 4 | +importjava.util.List; |
| 5 | +importjava.util.Objects; |
| 6 | +importjava.util.Optional; |
| 7 | + |
| 8 | +/** |
| 9 | + * @author: caos321 |
| 10 | + * @date: 31 October 2021 (Sunday) |
| 11 | + */ |
| 12 | +publicclassDepthFirstSearch { |
| 13 | +staticclassNode { |
| 14 | +privatefinalStringname; |
| 15 | +privatefinalList<Node>subNodes; |
| 16 | + |
| 17 | +publicNode(finalStringname) { |
| 18 | +this.name =name; |
| 19 | +this.subNodes =newArrayList<>(); |
| 20 | + } |
| 21 | + |
| 22 | +publicNode(finalStringname,finalList<Node>subNodes) { |
| 23 | +this.name =name; |
| 24 | +this.subNodes =subNodes; |
| 25 | + } |
| 26 | + |
| 27 | +publicStringgetName() { |
| 28 | +returnname; |
| 29 | + } |
| 30 | + |
| 31 | +publicList<Node>getSubNodes() { |
| 32 | +returnsubNodes; |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | +publicstaticOptional<Node>search(finalNodenode,finalStringname) { |
| 37 | +if (node.getName().equals(name)) { |
| 38 | +returnOptional.of(node); |
| 39 | + } |
| 40 | + |
| 41 | +returnnode.getSubNodes() |
| 42 | + .stream() |
| 43 | + .map(value ->search(value,name)) |
| 44 | + .flatMap(Optional::stream) |
| 45 | + .findAny(); |
| 46 | + } |
| 47 | + |
| 48 | +publicstaticvoidassertThat(finalObjectactual,finalObjectexpected) { |
| 49 | +if (!Objects.equals(actual,expected)) { |
| 50 | +thrownewAssertionError(String.format("expected=%s but was actual=%s",expected,actual)); |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | +publicstaticvoidmain(finalString[]args) { |
| 55 | +finalNoderootNode =newNode("A",List.of( |
| 56 | +newNode("B",List.of(newNode("D"),newNode("F",List.of( |
| 57 | +newNode("H"),newNode("I") |
| 58 | + )))), |
| 59 | +newNode("C",List.of(newNode("G"))), |
| 60 | +newNode("E") |
| 61 | + )); |
| 62 | + |
| 63 | + { |
| 64 | +finalStringexpected ="I"; |
| 65 | + |
| 66 | +finalNoderesult =search(rootNode,expected) |
| 67 | + .orElseThrow(() ->newAssertionError("Node not found!")); |
| 68 | + |
| 69 | +assertThat(result.getName(),expected); |
| 70 | + } |
| 71 | + |
| 72 | + { |
| 73 | +finalStringexpected ="G"; |
| 74 | + |
| 75 | +finalNoderesult =search(rootNode,expected) |
| 76 | + .orElseThrow(() ->newAssertionError("Node not found!")); |
| 77 | + |
| 78 | +assertThat(result.getName(),expected); |
| 79 | + } |
| 80 | + |
| 81 | + { |
| 82 | +finalStringexpected ="E"; |
| 83 | + |
| 84 | +finalNoderesult =search(rootNode,expected) |
| 85 | + .orElseThrow(() ->newAssertionError("Node not found!")); |
| 86 | + |
| 87 | +assertThat(result.getName(),expected); |
| 88 | + } |
| 89 | + } |
| 90 | +} |