File tree 2 files changed +75
-0
lines changed
2 files changed +75
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public int minimumSemesters (int N , int [][] relations ) {
3
+ Map <Integer , List <Integer >> map = new HashMap <>();
4
+ // A prerequisite counter for each course
5
+ int [] prereqs = new int [N + 1 ];
6
+
7
+ for (int [] relation : relations ) {
8
+ map .computeIfAbsent (relation [0 ], k -> new ArrayList <>()).add (relation [1 ]);
9
+ prereqs [relation [1 ]]++;
10
+ }
11
+
12
+ Queue <Integer > queue = new LinkedList <>();
13
+
14
+ // Add all the courses which have no prerequisite
15
+ // So that we can take those courses in first semester
16
+ for (int i = 1 ; i <= N ; i ++) {
17
+ if (prereqs [i ] == 0 ) {
18
+ queue .add (i );
19
+ }
20
+ }
21
+
22
+ int semester = 0 ;
23
+ while (!queue .isEmpty ()) {
24
+ int size = queue .size ();
25
+ while (size -- > 0 ) {
26
+ int course = queue .poll ();
27
+ // Decrement N as we have taken a course that is removed from the queue
28
+ N --;
29
+ for (int pre : map .getOrDefault (course , new ArrayList <>())) {
30
+ /*
31
+ If a course which depends upon the removed course had only the removed course as prereq then we can
32
+ add it to the queue
33
+ */
34
+ if (--prereqs [pre ] == 0 ) {
35
+ queue .add (pre );
36
+ }
37
+ }
38
+ }
39
+
40
+ // Semester over. New semester starts
41
+ semester ++;
42
+ }
43
+
44
+ return N == 0 ? semester : -1 ;
45
+ }
46
+ }
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public boolean isBipartite (int [][] graph ) {
3
+ int [] colors = new int [graph .length ];
4
+ Arrays .fill (colors , -1 );
5
+ Stack <Integer > stack = new Stack <>();
6
+
7
+ for (int i = 0 ; i < graph .length ; i ++) {
8
+ if (colors [i ] == -1 ) {
9
+ stack .push (i );
10
+ colors [i ] = 0 ;
11
+
12
+ while (!stack .isEmpty ()) {
13
+ Integer removed = stack .pop ();
14
+ for (Integer connect : graph [removed ]) {
15
+ if (colors [connect ] == -1 ) {
16
+ stack .push (connect );
17
+ colors [connect ] = colors [removed ] == 1 ? 0 : 1 ;
18
+ }
19
+ else if (colors [connect ] == colors [removed ]) {
20
+ return false ;
21
+ }
22
+ }
23
+ }
24
+ }
25
+ }
26
+
27
+ return true ;
28
+ }
29
+ }
You can’t perform that action at this time.
0 commit comments