Skip to content

Commit e37eb98

Browse files
committed
Fix
1 parent 832eeb9 commit e37eb98

File tree

2 files changed

+9
-3
lines changed

2 files changed

+9
-3
lines changed

src/main/java/com/thealgorithms/datastructures/graphs/KahnsAlgorithm.java

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff 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
}

src/test/java/com/thealgorithms/datastructures/graphs/KahnsAlgorithmTest.java

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff 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
}

0 commit comments

Comments
 (0)