File tree 1 file changed +26
-14
lines changed
1 file changed +26
-14
lines changed Original file line number Diff line number Diff line change @@ -4,23 +4,35 @@ public boolean isBipartite(int[][] graph) {
4
4
int [] color = new int [n ];
5
5
Arrays .fill (color , -1 );
6
6
for (int i = 0 ; i < n ; i ++) {
7
- if (color [i ] == -1 ) {
8
- Stack <Integer > stack = new Stack <>();
9
- stack .push (i );
10
- color [i ] = 0 ;
11
- while (!stack .isEmpty ()) {
12
- Integer node = stack .pop ();
13
- for (Integer neighbor : graph [node ]) {
14
- if (color [neighbor ] == -1 ) {
15
- stack .push (neighbor );
16
- color [neighbor ] = color [node ] ^ 1 ;
17
- }
18
- else if (color [neighbor ] == color [node ]) {
19
- return false ;
20
- }
7
+ if (color [i ] == -1 && !bipartiteCheck (graph , i , color )) {
8
+ return false ;
9
+ }
10
+ }
11
+ return true ;
12
+ }
13
+
14
+ private boolean bipartiteCheck (int [][] graph , int node , int [] color ) {
15
+ Queue <Integer > queue = new LinkedList <>();
16
+ queue .add (node );
17
+ int currColor = 0 ;
18
+ while (!queue .isEmpty ()) {
19
+ int size = queue .size ();
20
+ while (size -- > 0 ) {
21
+ int removed = queue .remove ();
22
+ if (color [removed ] != -1 ) {
23
+ if (color [removed ] != currColor ) {
24
+ return false ;
25
+ }
26
+ continue ;
27
+ }
28
+ color [removed ] = currColor ;
29
+ for (int conn : graph [removed ]) {
30
+ if (color [conn ] == -1 ) {
31
+ queue .add (conn );
21
32
}
22
33
}
23
34
}
35
+ currColor = currColor == 1 ? 0 : 1 ;
24
36
}
25
37
return true ;
26
38
}
You can’t perform that action at this time.
0 commit comments