Skip to content

Commit 7be2100

Browse files
authored
Merge pull request #502 from taojin1992/patch-3
2 parents 79de5b2 + ff02337 commit 7be2100

File tree

1 file changed

+78
-2
lines changed

1 file changed

+78
-2
lines changed

problems/785.is-graph-bipartite.md

Lines changed: 78 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,10 @@ class Solution:
137137

138138
### 代码
139139

140+
代码支持:Python3,Java
141+
142+
Python3 Code:
143+
140144
```py
141145
class UF:
142146
def __init__(self, n):
@@ -163,13 +167,85 @@ class Solution:
163167
return True
164168
```
165169

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+
166242

167243
**复杂度分析**
168244

169245
令 v 和 e 为图中的顶点数和边数。
170246

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
173249

174250
## 相关问题
175251

0 commit comments

Comments
 (0)