70 lines
1.8 KiB
Java
70 lines
1.8 KiB
Java
package ch.usi.inf.sp.graph;
|
|
|
|
|
|
import java.util.ArrayList;
|
|
import java.util.Collections;
|
|
import java.util.List;
|
|
|
|
|
|
public class DiGraph<N extends Node<E>, E extends Edge<N>> {
|
|
|
|
private final ArrayList<N> nodes;
|
|
private final ArrayList<E> edges;
|
|
|
|
|
|
public DiGraph() {
|
|
nodes = new ArrayList<N>();
|
|
edges = new ArrayList<E>();
|
|
}
|
|
|
|
public void addNode(N node) {
|
|
nodes.add(node);
|
|
}
|
|
|
|
public void addEdge(E edge) {
|
|
edges.add(edge);
|
|
}
|
|
|
|
public void connect(N from, E edge, N to) {
|
|
if (!nodes.contains(from)) {
|
|
throw new IllegalStateException("Graph does not contain from node.");
|
|
}
|
|
if (!nodes.contains(to)) {
|
|
throw new IllegalStateException("Graph does not contain to node.");
|
|
}
|
|
if (!edges.contains(edge)) {
|
|
throw new IllegalStateException("Graph does not contain edge.");
|
|
}
|
|
if (from.getOutEdges().contains(edge)) {
|
|
throw new IllegalStateException("From node already has this edge as out edge");
|
|
}
|
|
if (to.getInEdges().contains(edge)) {
|
|
throw new IllegalStateException("To node already has this edge as in edge");
|
|
}
|
|
edge.setFrom(from);
|
|
edge.setTo(to);
|
|
from.addOutEdge(edge);
|
|
to.addInEdge(edge);
|
|
}
|
|
|
|
public List<E> getEdges() {
|
|
return Collections.unmodifiableList(edges);
|
|
}
|
|
|
|
public List<N> getNodes() {
|
|
return Collections.unmodifiableList(nodes);
|
|
}
|
|
|
|
public String toString() {
|
|
final StringBuffer sb = new StringBuffer("digraph G {\n");
|
|
for (final Node node : nodes) {
|
|
sb.append(" "+node+"\n");
|
|
}
|
|
for (final Edge edge : edges) {
|
|
sb.append(" "+edge+"\n");
|
|
}
|
|
sb.append("}\n");
|
|
return sb.toString();
|
|
}
|
|
}
|