-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathCourse_Schedule.java
59 lines (45 loc) · 2.31 KB
/
Course_Schedule.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
//Leetcode 207. Course Schedule
//Question - https://leetcode.com/problems/course-schedule/
//Used Kahn's Topological Sort
class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
/*Input Description -
numCourses ==> number of nodes in the graph
prerequisites ==> 1. each row is a pair of vertices
2. represents edges in the graph
3. edge direction is prerequisites[row][1] --> prerequisites[row][0]
4. NOTE - (prerequisites.length != numCourses) because (prerequisites.length==number of edges) & (numCourses==vertices)
*/
int inDegree[] = new int[numCourses]; //keep track of indegrees of all nodes
Arrays.fill(inDegree,0);
for(int i=0;i<prerequisites.length;i++){
inDegree[prerequisites[i][0]]++;
}
Queue<Integer> inDegree0 = new LinkedList<>(); //to add vertices of inDegree 0
for(int i=0;i<numCourses;i++){
if(inDegree[i]==0) inDegree0.add(i);
}
int vertexCnt = 0; //needed to check if cycle present or not
/*for a cyclic component in a garph the inDegree will never be 0 ==> vertices in that component will never be added in the queue ==>
vertexCnt will not increment for those vertices ==> (vertexCnt != numCourses)
*/
while(!inDegree0.isEmpty()){
int curr = inDegree0.poll();
ArrayList<Integer> neighbours = findNeighbours(prerequisites,curr); //removing this vertex from graph
for(int neighbour : neighbours){
//reflecting the change after removing the vertex
if(--inDegree[neighbour]==0) inDegree0.add(neighbour);
}
vertexCnt++;
}
if(vertexCnt==numCourses) return true; //no cycles in graph
else return false; //cycles in garph
}
public ArrayList<Integer> findNeighbours(int[][] prerequisites,int v){
ArrayList<Integer> neighbour = new ArrayList<>();
for(int i=0 ; i<prerequisites.length ; i++){
if(prerequisites[i][1]==v) neighbour.add(prerequisites[i][0]);
}
return neighbour;
}
}