File tree Expand file tree Collapse file tree 2 files changed +9
-3
lines changed
main/java/com/thealgorithms/datastructures/graphs
test/java/com/thealgorithms/datastructures/graphs Expand file tree Collapse file tree 2 files changed +9
-3
lines changed Original file line number Diff line number Diff line change @@ -103,6 +103,7 @@ void calculateInDegree() {
103103 * (u, v), vertex u appears before vertex v in the ordering.
104104 *
105105 * @return an ArrayList of vertices in topological order
106+ * @throws IllegalStateException if the graph contains a cycle
106107 */
107108 ArrayList <E > topSortOrder () {
108109 calculateInDegree ();
@@ -115,10 +116,13 @@ ArrayList<E> topSortOrder() {
115116 }
116117
117118 ArrayList <E > answer = new ArrayList <>();
119+ int processedVertices = 0 ;
118120
119121 while (!q .isEmpty ()) {
120122 E current = q .poll ();
121123 answer .add (current );
124+ processedVertices ++;
125+
122126 for (E adjacent : graph .getAdjacents (current )) {
123127 inDegree .put (adjacent , inDegree .get (adjacent ) - 1 );
124128 if (inDegree .get (adjacent ) == 0 ) {
@@ -127,6 +131,10 @@ ArrayList<E> topSortOrder() {
127131 }
128132 }
129133
134+ if (processedVertices != graph .getVertices ().size ()) {
135+ throw new IllegalStateException ("Graph contains a cycle, topological sort not possible" );
136+ }
137+
130138 return answer ;
131139 }
132140}
Original file line number Diff line number Diff line change @@ -72,9 +72,7 @@ void testSingleNodeGraph() {
7272 graph .addEdge ("a" , "a" ); // self-loop
7373
7474 TopologicalSort <String > topSort = new TopologicalSort <>(graph );
75- ArrayList <String > result = topSort .topSortOrder ();
7675
77- String [] expectedOrder = {};
78- assertArrayEquals (expectedOrder , result .toArray ());
76+ assertThrows (IllegalStateException .class , () -> topSort .topSortOrder ());
7977 }
8078}
You can’t perform that action at this time.
0 commit comments