File tree 2 files changed +55
-0
lines changed
lcof2/剑指 Offer II 106. 二分图
2 files changed +55
-0
lines changed Original file line number Diff line number Diff line change @@ -183,6 +183,36 @@ func isBipartite(graph [][]int) bool {
183
183
}
184
184
```
185
185
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
+
186
216
<!-- tabs:end -->
187
217
188
218
<!-- solution:end -->
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments