DFS-based topological sort. A valid sort is the reverse of the post-order DFA traversal. Amazingly simple but true. For sorting, I'm not following convention here since ANTLR needs the opposite. Here's what I assume for sorting: If there exists an edge u -> v then u depends on v and v
()
| 88 | * I want. |
| 89 | */ |
| 90 | public List<T> sort() { |
| 91 | Set<Node<T>> visited = new OrderedHashSet<Node<T>>(); |
| 92 | ArrayList<T> sorted = new ArrayList<T>(); |
| 93 | while ( visited.size() < nodes.size() ) { |
| 94 | // pick any unvisited node, n |
| 95 | Node<T> n = null; |
| 96 | for (Node<T> tNode : nodes.values()) { |
| 97 | n = tNode; |
| 98 | if ( !visited.contains(n) ) break; |
| 99 | } |
| 100 | if (n!=null) { // if at least one unvisited |
| 101 | DFS(n, visited, sorted); |
| 102 | } |
| 103 | } |
| 104 | return sorted; |
| 105 | } |
| 106 | |
| 107 | public void DFS(Node<T> n, Set<Node<T>> visited, ArrayList<T> sorted) { |
| 108 | if ( visited.contains(n) ) return; |