@@ -163,13 +163,83 @@ class Solution:
163
163
return True
164
164
```
165
165
166
+ ``` java
167
+ // weighted quick-union with path compression
168
+ class Solution {
169
+ class UF {
170
+ int numOfUnions; // number of unions
171
+ int [] parent;
172
+ int [] size;
173
+
174
+ UF (int numOfElements) {
175
+ numOfUnions = numOfElements;
176
+ parent = new int [numOfElements];
177
+ size = new int [numOfElements];
178
+ for (int i = 0 ; i < numOfElements ; i ++) {
179
+ parent[i] = i;
180
+ size[i] = 1 ;
181
+ }
182
+ }
183
+
184
+ // find the head/representative of x
185
+ int find(int x) {
186
+ while (x != parent [x ]) {
187
+ parent[x] = parent[parent[x]];
188
+ x = parent[x];
189
+ }
190
+ return x;
191
+ }
192
+
193
+ void union(int p, int q) {
194
+ int headOfP = find(p);
195
+ int headOfQ = find(q);
196
+ if (headOfP == headOfQ ) {
197
+ return ;
198
+ }
199
+ // connect the small tree to the larger tree
200
+ if (size [headOfP ] < size [headOfQ ]) {
201
+ parent[headOfP] = headOfQ; // set headOfP's parent to be headOfQ
202
+ size[headOfQ] += size[headOfP];
203
+ } else {
204
+ parent[headOfQ] = headOfP;
205
+ size[headOfP] += size[headOfQ];
206
+ }
207
+ numOfUnions -= 1 ;
208
+ }
209
+
210
+ boolean connected(int p, int q) {
211
+ return find (p ) == find (q );
212
+ }
213
+ }
214
+
215
+ public boolean isBipartite (int [][] graph ) {
216
+ int n = graph. length;
217
+ UF unionfind = new UF (n);
218
+ // i is what node each adjacent list is for
219
+ for (int i = 0 ; i < n; i++ ) {
220
+ // i's neighbors
221
+ for (int neighbor : graph[i]) {
222
+ // i should not be in the union of its neighbors
223
+ if (unionfind. connected(i, neighbor)) {
224
+ return false ;
225
+ }
226
+ // add into unions
227
+ unionfind. union(graph[i][0 ], neighbor);
228
+ }
229
+ }
230
+
231
+ return true ;
232
+ }
233
+
234
+ ```
235
+
166
236
167
237
** 复杂度分析**
168
238
169
239
令 v 和 e 为图中的顶点数和边数。
170
240
171
- - 时间复杂度:$O(v+e)$
172
- - 空间复杂度:$O(v+e)$
241
+ - 时间复杂度:$O(v+ e)$, using weighted quick-union with path compression, where union, find and connected are $ O ( 1 )$, constructing unions takes $ O ( v )$
242
+ - 空间复杂度:$O (v )$ for auxiliary union-find space int[] parent, int[] space
173
243
174
244
## 相关问题
175
245
0 commit comments