com.jn.langx.util.collection.graph.DAG Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of langx-java Show documentation
Show all versions of langx-java Show documentation
Java lang extensions for java6+, a supplement to , replacement of a Guava, commons-lang.
Core utilities, Collection utilities, IO utilities, Cache, Configuration library ...
package com.jn.langx.util.collection.graph;
import java.util.List;
public class DAG extends Graph {
public boolean addEdge(Vertex from, Vertex to, int weight) {
if (!hasVertex(from.getName())) {
addVertex(from);
}
if (!hasVertex(to.getName())) {
addVertex(to);
}
Edge e = new Edge(from, to, weight);
if (from.findEdge(to) != null) {
// 已有该 edge,则不再添加
return false;
} else {
from.addEdge(e);
to.addEdge(e);
final List cycle = Graphs.detectCycle(to);
if (cycle != null) {
// remove edge which introduced cycle
removeEdge(from, to);
final String msg = "Edge between '" + from + "' and '" + to + "' introduces to cycle in the graph";
throw new CycleDetectedException(msg, cycle);
}
edges.add(e);
return true;
}
}
}