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() {
103
103
* (u, v), vertex u appears before vertex v in the ordering.
104
104
*
105
105
* @return an ArrayList of vertices in topological order
106
+ * @throws IllegalStateException if the graph contains a cycle
106
107
*/
107
108
ArrayList <E > topSortOrder () {
108
109
calculateInDegree ();
@@ -115,10 +116,13 @@ ArrayList<E> topSortOrder() {
115
116
}
116
117
117
118
ArrayList <E > answer = new ArrayList <>();
119
+ int processedVertices = 0 ;
118
120
119
121
while (!q .isEmpty ()) {
120
122
E current = q .poll ();
121
123
answer .add (current );
124
+ processedVertices ++;
125
+
122
126
for (E adjacent : graph .getAdjacents (current )) {
123
127
inDegree .put (adjacent , inDegree .get (adjacent ) - 1 );
124
128
if (inDegree .get (adjacent ) == 0 ) {
@@ -127,6 +131,10 @@ ArrayList<E> topSortOrder() {
127
131
}
128
132
}
129
133
134
+ if (processedVertices != graph .getVertices ().size ()) {
135
+ throw new IllegalStateException ("Graph contains a cycle, topological sort not possible" );
136
+ }
137
+
130
138
return answer ;
131
139
}
132
140
}
Original file line number Diff line number Diff line change @@ -72,9 +72,7 @@ void testSingleNodeGraph() {
72
72
graph .addEdge ("a" , "a" ); // self-loop
73
73
74
74
TopologicalSort <String > topSort = new TopologicalSort <>(graph );
75
- ArrayList <String > result = topSort .topSortOrder ();
76
75
77
- String [] expectedOrder = {};
78
- assertArrayEquals (expectedOrder , result .toArray ());
76
+ assertThrows (IllegalStateException .class , () -> topSort .topSortOrder ());
79
77
}
80
78
}
You can’t perform that action at this time.
0 commit comments