Course Schedule (Cycle Detection) in Java: Explanation & Practice
Check if all courses can be finished
Problem summary
There are numCourses courses with prerequisites. Check if it's possible to finish all courses. This is essentially cycle detection in a directed graph!
Starter code
public class Main {
public static void main(String[] args) {
int numCourses = 2;
int[][] prereqs = {{1, 0}}; // [1,0] means take 0 before 1
// Build adjacency list
// Check for cycle using DFS with 3 states:
// 0=unvisited, 1=visiting, 2=visited
// Print: Can finish: true
}
}Expected output and test cases
- 2 courses, [1,0]
Can finish: true
- 2 courses, [1,0],[0,1] cycle
Can finish: false
- 3 courses, no prereqs
Can finish: true
Hints
- Build adjacency list: course → list of dependent courses
- DFS with 3 states: unvisited, visiting, visited
- If we visit a 'visiting' node, we found a cycle!
- Mark as 'visited' after all descendants processed
Related Data Structures & Algorithms exercises
- Practice Number of Islands in Java
- Practice Clone Graph in Java
- Practice Word Ladder (Shortest Path) in Java
Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler