/** * Performs the sort. * * @param dag the DAG to sort * @param vertices map of vertices and references * @param roots roots in the graph * @return the total ordering calculated by the topological sort * @throws CycleException if a cycle is detected */ private List<Vertex<T>> sort(DirectedGraph<T> dag, Map<Vertex<T>, AtomicInteger> vertices, List<Vertex<T>> roots) throws CycleException { List<Vertex<T>> visited = new ArrayList<Vertex<T>>(); int num = vertices.size() + roots.size(); while (!roots.isEmpty()) { Vertex<T> v = roots.remove(roots.size() - 1); visited.add(v); List<Vertex<T>> outgoing = dag.getOutgoingAdjacentVertices(v); for (Vertex<T> child : outgoing) { AtomicInteger count = vertices.get(child); if (count.decrementAndGet() == 0) { // add child to root list as all parents are processed roots.add(child); } } } if (visited.size() != num) { throw new CycleException(); } return visited; }
/** * Performs the sort. * * @param dag the DAG to sort * @param vertices map of vertices and references * @param roots roots in the graph * @return the total ordering calculated by the topological sort * @throws CycleException if a cycle is detected */ private List<Vertex<T>> sort(DirectedGraph<T> dag, Map<Vertex<T>, AtomicInteger> vertices, List<Vertex<T>> roots) throws CycleException { List<Vertex<T>> visited = new ArrayList<>(); int num = vertices.size() + roots.size(); while (!roots.isEmpty()) { Vertex<T> v = roots.remove(roots.size() - 1); visited.add(v); List<Vertex<T>> outgoing = dag.getOutgoingAdjacentVertices(v); for (Vertex<T> child : outgoing) { AtomicInteger count = vertices.get(child); if (count.decrementAndGet() == 0) { // add child to root list as all parents are processed roots.add(child); } } } if (visited.size() != num) { throw new CycleException(); } return visited; }
/** * Performs the sort. * * @param dag the DAG to sort * @param vertices map of vertices and references * @param roots roots in the graph * @return the total ordering calculated by the topological sort * @throws CycleException if a cycle is detected */ private List<Vertex<T>> sort(DirectedGraph<T> dag, Map<Vertex<T>, AtomicInteger> vertices, List<Vertex<T>> roots) throws CycleException { List<Vertex<T>> visited = new ArrayList<>(); int num = vertices.size() + roots.size(); while (!roots.isEmpty()) { Vertex<T> v = roots.remove(roots.size() - 1); visited.add(v); List<Vertex<T>> outgoing = dag.getOutgoingAdjacentVertices(v); for (Vertex<T> child : outgoing) { AtomicInteger count = vertices.get(child); if (count.decrementAndGet() == 0) { // add child to root list as all parents are processed roots.add(child); } } } if (visited.size() != num) { throw new CycleException(); } return visited; }