Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Add BreadthFirstSearch#2801

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
Merged
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 80 additions & 0 deletionsSearches/BreadthFirstSearch.java
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -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<Node> search(final Node node, final String name) {
if (node.getName().equals(name)) {
return Optional.of(node);
}

List<Node> 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);
}
}
}

[8]ページ先頭

©2009-2025 Movatter.jp