File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change 1+ // Time Complexity : O(N) and Space O(N) Heap space,
2+ // Advantage over stack approach: handle cycle detection
3+
4+ class Solution {
5+ public boolean isCycle (int numCourses , int [][] prerequisites ) {
6+ if (numCourses <= 1 )return true ;
7+ try {
8+
9+ int d [] = new int [numCourses ];
10+ // Graph as Adj List
11+ LinkedList <Integer > [] adj = new LinkedList [numCourses ];
12+ for (int vertex = 0 ; vertex < numCourses ; vertex ++){
13+ adj [vertex ] = new LinkedList <Integer >();
14+ }
15+
16+ for (int [] edge : prerequisites ){
17+ d [edge [1 ]]++;
18+ adj [edge [0 ]].add (edge [1 ]); // directed
19+ }
20+ LinkedList <Integer > queue = new LinkedList <>();
21+ for (int vertex = 0 ; vertex < numCourses ; vertex ++){
22+ if (d [vertex ] == 0 ){
23+ queue .add (vertex );
24+ }
25+ }
26+ LinkedList <Integer > topologicalOrder = new LinkedList <>();
27+ while (!queue .isEmpty ()){
28+ int parent = (Integer )queue .removeFirst ();
29+ topologicalOrder .add (parent );
30+ for (int child : adj [parent ]){
31+ d [child ]--;
32+ if (d [child ] == 0 ){
33+ queue .addLast (child );
34+ }
35+ }
36+ }
37+ return topologicalOrder .size () == numCourses ;
38+ }catch (Exception exc ){
39+ // Logger.logException to centralized monitoring system
40+ return false ;
41+ }
42+ }
43+ }
44+
You can’t perform that action at this time.
0 commit comments