io.convergence_platform.common.dag.DirectedAcyclicGraph Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of service-lib Show documentation
Show all versions of service-lib Show documentation
Holds the common functionality needed by all Convergence Platform-based services written in Java.
The newest version!
package io.convergence_platform.common.dag;
// Adapted from https://www.javatpoint.com/topological-sorting
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class DirectedAcyclicGraph> {
private int nodeCount = 0;
private boolean[][] adjMatrix = null;
private List nodes = null;
public DirectedAcyclicGraph() {
}
public DirectedAcyclicGraph(List nodes) {
initialize(nodes);
}
protected void initialize(List nodes) {
this.nodes = nodes;
this.nodeCount = nodes.size();
adjMatrix = new boolean[nodeCount][nodeCount];
for (Type node : nodes) {
List dependencies = node.getDependencies();
if (dependencies != null) {
for (Type dep : dependencies) {
addEdge(node, dep);
}
}
}
}
public void addEdge(int node, int dependentNode) {
// With the use of add() a new edge will be added into the Directed Acyclic Graph
adjMatrix[dependentNode][node] = true;
}
public void addEdge(Type node, Type dependentNode) {
int n = nodes.indexOf(node);
int d = nodes.indexOf(dependentNode);
addEdge(n, d);
}
private void topologicalSortUtil(int v, boolean[] visited, Stack stack) {
visited[v] = true;
for (int index = 0; index < nodeCount; index++) {
if (adjMatrix[v][index]) {
if (!visited[index]) {
topologicalSortUtil(index, visited, stack);
}
}
}
stack.push(v);
}
public List topologicalSort() {
Stack stack = new Stack<>();
boolean[] visited = new boolean[nodeCount];
for (int i = 0; i < visited.length; i++) {
if (!visited[i]) {
topologicalSortUtil(i, visited, stack);
}
}
List result = new ArrayList<>();
while (!stack.empty()) {
int index = stack.pop();
result.add(nodes.get(index));
}
return result;
}
}