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