|
1 | 1 | package com.thealgorithms.graph; |
2 | 2 |
|
3 | 3 | import static org.junit.jupiter.api.Assertions.assertArrayEquals; |
| 4 | +import static org.junit.jupiter.api.Assertions.assertEquals; |
| 5 | +import static org.junit.jupiter.api.Assertions.assertTrue; |
| 6 | + |
| 7 | +import java.util.HashMap; |
| 8 | +import java.util.Map; |
4 | 9 |
|
5 | 10 | import org.junit.jupiter.api.BeforeEach; |
6 | 11 | import org.junit.jupiter.api.Test; |
@@ -78,8 +83,20 @@ public void testComplexGraph() { |
78 | 83 |
|
79 | 84 | int[] result = topologicalSortDFS.findOrder(numCourses, prerequisites); |
80 | 85 |
|
81 | | - // Valid order: [5, 4, 2, 3, 1, 0] |
82 | | - int[] expected = { 5, 4, 2, 3, 1, 0 }; |
83 | | - assertArrayEquals(expected, result, "Valid topological order expected such as [5, 4, 2, 3, 1, 0]."); |
| 86 | + // Validate topological order |
| 87 | + assertEquals(numCourses, result.length, "Should include all courses."); |
| 88 | + |
| 89 | + // Check that each prerequisite comes before its dependent |
| 90 | + Map<Integer, Integer> position = new HashMap<>(); |
| 91 | + for (int i = 0; i < result.length; i++) { |
| 92 | + position.put(result[i], i); |
| 93 | + } |
| 94 | + |
| 95 | + for (int[] edge : prerequisites) { |
| 96 | + int course = edge[0]; |
| 97 | + int prereq = edge[1]; |
| 98 | + assertTrue(position.get(prereq) < position.get(course), |
| 99 | + String.format("Course %d should come after prerequisite %d", course, prereq)); |
| 100 | + } |
84 | 101 | } |
85 | 102 | } |
0 commit comments