Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 28af7f8

Browse files
feat: add swift implementation to lcof2 problem: No.106 (doocs#3619)
1 parent fdca4b4 commit 28af7f8

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

‎lcof2/剑指 Offer II 106. 二分图/README.md‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,36 @@ func isBipartite(graph [][]int) bool {
183183
}
184184
```
185185

186+
#### Swift
187+
188+
```swift
189+
class Solution {
190+
private var parent: [Int] = []
191+
192+
func isBipartite(_ graph: [[Int]]) -> Bool {
193+
let n = graph.count
194+
parent = Array(0..<n)
195+
196+
for u in 0..<n {
197+
for v in graph[u] {
198+
if find(u) == find(v) {
199+
return false
200+
}
201+
parent[find(v)] = find(graph[u][0])
202+
}
203+
}
204+
return true
205+
}
206+
207+
private func find(_ x: Int) -> Int {
208+
if parent[x] != x {
209+
parent[x] = find(parent[x])
210+
}
211+
return parent[x]
212+
}
213+
}
214+
```
215+
186216
<!-- tabs:end -->
187217

188218
<!-- solution:end -->
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution {
2+
private var parent: [Int] = []
3+
4+
func isBipartite(_ graph: [[Int]]) -> Bool {
5+
let n = graph.count
6+
parent = Array(0..<n)
7+
8+
for u in 0..<n {
9+
for v in graph[u] {
10+
if find(u) == find(v) {
11+
return false
12+
}
13+
parent[find(v)] = find(graph[u][0])
14+
}
15+
}
16+
return true
17+
}
18+
19+
private func find(_ x: Int) -> Int {
20+
if parent[x] != x {
21+
parent[x] = find(parent[x])
22+
}
23+
return parent[x]
24+
}
25+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /