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