1 package org.codehaus.plexus.util.dag;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 import java.util.HashMap;
20 import java.util.LinkedList;
21 import java.util.List;
22 import java.util.Map;
23
24
25
26
27
28 public class TopologicalSorter
29 {
30
31 private final static Integer NOT_VISITED = 0;
32
33 private final static Integer VISITING = 1;
34
35 private final static Integer VISITED = 2;
36
37
38
39
40
41 public static List<String> sort( final DAG graph )
42 {
43 return dfs( graph );
44 }
45
46 public static List<String> sort( final Vertex vertex )
47 {
48
49 final List<String> retValue = new LinkedList<>();
50
51 dfsVisit( vertex, new HashMap<Vertex, Integer>(), retValue );
52
53 return retValue;
54 }
55
56 private static List<String> dfs( final DAG graph )
57 {
58
59 final List<String> retValue = new LinkedList<>();
60 final Map<Vertex, Integer> vertexStateMap = new HashMap<>();
61
62 for ( Vertex vertex : graph.getVertices() )
63 {
64 if ( isNotVisited( vertex, vertexStateMap ) )
65 {
66 dfsVisit( vertex, vertexStateMap, retValue );
67 }
68 }
69
70 return retValue;
71 }
72
73 private static boolean isNotVisited( final Vertex vertex, final Map<Vertex, Integer> vertexStateMap )
74 {
75 final Integer state = vertexStateMap.get( vertex );
76
77 return ( state == null ) || NOT_VISITED.equals( state );
78 }
79
80 private static void dfsVisit( final Vertex vertex, final Map<Vertex, Integer> vertexStateMap,
81 final List<String> list )
82 {
83 vertexStateMap.put( vertex, VISITING );
84
85 for ( Vertex v : vertex.getChildren() )
86 {
87 if ( isNotVisited( v, vertexStateMap ) )
88 {
89 dfsVisit( v, vertexStateMap, list );
90 }
91 }
92
93 vertexStateMap.put( vertex, VISITED );
94
95 list.add( vertex.getLabel() );
96 }
97
98 }