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

  1. Build adjacency list: course → list of dependent courses
  2. DFS with 3 states: unvisited, visiting, visited
  3. If we visit a 'visiting' node, we found a cycle!
  4. Mark as 'visited' after all descendants processed

Related Data Structures & Algorithms exercises

Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler