Initial Setup

This commit is contained in:
Niklas Birk 2019-03-24 11:58:30 +01:00
commit 600cc73df6
3 changed files with 161 additions and 0 deletions

View File

@ -0,0 +1,28 @@
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
public class BreadthFirstSearch
{
public Node breadthFirstSearch(List<Node> nodes, Node target)
{
var newNodes = new ArrayList<Node>();
for (Node node : nodes)
{
if (target.equals(node))
{
return node;
}
newNodes.addAll(node.getChildren());
}
if (newNodes.isEmpty())
{
return breadthFirstSearch(newNodes, target);
}
return null;
}
}

31
src/Main.java Normal file
View File

@ -0,0 +1,31 @@
import java.util.List;
public class Main
{
public static void main(String[] args)
{
var root = new Node(0);
var childOne = new Node(1);
var childTwo = new Node(2);
var childThree = new Node(3);
var childrenLayer1 = List.of(childOne, childTwo, childThree);
root.addChildren(childrenLayer1);
var childFour = new Node(4);
var childFive = new Node(5);
var children2 = List.of(childFour, childFive);
childOne.addChildren(children2);
var childSix = new Node(6);
var children3 = List.of(childSix);
childTwo.addChildren(children3);
System.out.println(root);
System.out.println(new BreadthFirstSearch().breadthFirstSearch(List.of(root), new Node(2)));
}
}

102
src/Node.java Normal file
View File

@ -0,0 +1,102 @@
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class Node
{
private Object value;
private Node parent;
private List<Node> children;
public Node(Object value)
{
this(value, new ArrayList<>());
}
public Node(Object value, List<Node> children)
{
this.value = value;
this.children = children;
for (Node child : children)
{
child.setParent(this);
}
}
public void addChildren(List<Node> children)
{
this.children.addAll(children);
}
public void addChild(Node child)
{
this.children.add(child);
}
public void removeChild(Node child)
{
this.children.remove(child);
}
public Object getValue()
{
return value;
}
public void setParent(Node parent)
{
this.parent = parent;
}
public Node getParent()
{
return parent;
}
public List<Node> getChildren()
{
return children;
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
Node node = (Node) o;
return value.equals(node.value);
}
@Override
public int hashCode()
{
return Objects.hash(value);
}
@Override
public String toString()
{
StringBuilder builder = new StringBuilder();
for (Node child : children)
{
builder.append(this.value).append(" -> ").append(child.getValue()).append("\n");
}
for (Node child : children)
{
builder.append(child);
}
return builder.toString();
}
}