1
+ package leetcode .editor .en .Q785 ;
2
+
3
+ import java .util .*;
4
+
5
+ import javafx .util .Pair ;
6
+
7
+ //leetcode submit region begin(Prohibit modification and deletion)
8
+ class Solution {
9
+
10
+ private static final int GRAY = 0 ;
11
+ private static final int BLUE = 1 ;
12
+ private static final int GREEN = 2 ;
13
+
14
+ public boolean isBipartite (int [][] graph ) {
15
+ HashMap <Integer , Integer > colors = new HashMap <>();
16
+ HashMap <Integer , HashSet <Integer >> adjList = makeAdjList (graph );
17
+ for (int i = 0 ; i < graph .length ; i ++) {
18
+ colors .put (i , GRAY );
19
+ }
20
+ for (int i = 0 ; i < graph .length ; i ++) {
21
+ if (colors .get (i ) != GRAY ) continue ;
22
+ if (!checkBipartition (i , adjList , colors )) return false ;
23
+ }
24
+ return true ;
25
+ }
26
+
27
+ private boolean checkBipartition (int root ,
28
+ HashMap <Integer , HashSet <Integer >> adjList ,
29
+ HashMap <Integer , Integer > colors ) {
30
+ Queue <int []> queue = new LinkedList <>();
31
+ queue .add (new int []{root , BLUE });
32
+ HashSet <Integer > visited = new HashSet <>();
33
+ while (!queue .isEmpty ()) {
34
+ int size = queue .size ();
35
+ for (int i = 0 ; i < size ; i ++) {
36
+ int [] shouldBeInfo = queue .poll ();
37
+ int node = shouldBeInfo [0 ];
38
+ int color = shouldBeInfo [1 ];
39
+ colors .put (node , color );
40
+ visited .add (node );
41
+ if (!adjList .containsKey (node )) continue ;
42
+ HashSet <Integer > connected = adjList .get (node );
43
+ int newColor = color == BLUE ? GREEN : BLUE ;
44
+ for (int next : connected ) {
45
+ if (colors .get (next ) != GRAY && colors .get (next ) != newColor ) {
46
+ return false ;
47
+ }
48
+ if (!visited .contains (next )) queue .add (new int []{next , newColor });
49
+ }
50
+ }
51
+ }
52
+ return true ;
53
+
54
+ }
55
+
56
+ private HashMap <Integer , HashSet <Integer >> makeAdjList (int [][] graph ) {
57
+ HashMap <Integer , HashSet <Integer >> adjList = new HashMap <>();
58
+ for (int i = 0 ; i < graph .length ; i ++) {
59
+ int from = i ;
60
+ for (int to : graph [i ]) {
61
+ adjList .computeIfAbsent (from , (v ) -> new HashSet <>()).add (to );
62
+ adjList .computeIfAbsent (to , (v ) -> new HashSet <>()).add (from );
63
+ }
64
+ }
65
+ return adjList ;
66
+ }
67
+ }
68
+ //leetcode submit region end(Prohibit modification and deletion)
69
+
70
+
71
+ public class IsGraphBipartite extends Solution {
72
+ }
0 commit comments