shriyanshi24jindal

Course Schedule

Mar 29th, 2026
127
0
Never
Not a member of GistPad yet? Sign Up, it unlocks many cool features!
Java 8.62 KB | None | 0 0
  1. class Solution {
  2. public boolean canFinish(int numCourses, int[][] prerequisites) {
  3. if(prerequisites.length == 0)
  4. return true;
  5.  
  6. // Step-1 Create a adjacency list
  7. ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
  8. for(int i=0; i<numCourses; i++)
  9. {
  10. adj.add(new ArrayList<>());
  11. }
  12.  
  13. // Step-2 Fill adjacency list and indegree array
  14. int[] indegree = new int[numCourses];
  15. for(int[] edge : prerequisites)
  16. {
  17. int u = edge[1];
  18. int v = edge[0];
  19.  
  20. adj.get(u).add(v);
  21. indegree[v]++;
  22. }
  23.  
  24. // Step-3 Find courses whose indegree is 0, add it to queue
  25. Queue<Integer> q = new LinkedList<>();
  26. for(int i=0; i<indegree.length; i++)
  27. {
  28. if(indegree[i] == 0)
  29. q.add(i);
  30. }
  31.  
  32. // Step-4: Process queue
  33. int count = 0;
  34. while(!q.isEmpty())
  35. {
  36. int node = q.poll();
  37. count++;
  38.  
  39. for(int u : adj.get(node))
  40. {
  41. indegree[u]--;
  42. if(indegree[u] == 0)
  43. q.add(u);
  44. }
  45. }
  46.  
  47. // if cycle exisits then we cannot finish all courses
  48. if(count != numCourses)
  49. return false;
  50. return true;
  51. }
  52. }
RAW Paste Data Copied