Skip to content

Commit c80128c

Browse files
authored
feat: add swift implementation to lcof2 problem: No.113 (#3691)
1 parent 3f74e52 commit c80128c

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed

lcof2/剑指 Offer II 113. 课程顺序/README.md

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -269,6 +269,46 @@ public class Solution {
269269
}
270270
```
271271

272+
#### Swift
273+
274+
```swift
275+
class Solution {
276+
func findOrder(_ numCourses: Int, _ prerequisites: [[Int]]) -> [Int] {
277+
var graph = Array(repeating: [Int](), count: numCourses)
278+
var indegree = Array(repeating: 0, count: numCourses)
279+
280+
for prereq in prerequisites {
281+
let course = prereq[0]
282+
let prereqCourse = prereq[1]
283+
graph[prereqCourse].append(course)
284+
indegree[course] += 1
285+
}
286+
287+
var queue = [Int]()
288+
for i in 0..<numCourses {
289+
if indegree[i] == 0 {
290+
queue.append(i)
291+
}
292+
}
293+
294+
var order = [Int]()
295+
while !queue.isEmpty {
296+
let course = queue.removeFirst()
297+
order.append(course)
298+
299+
for nextCourse in graph[course] {
300+
indegree[nextCourse] -= 1
301+
if indegree[nextCourse] == 0 {
302+
queue.append(nextCourse)
303+
}
304+
}
305+
}
306+
307+
return order.count == numCourses ? order : []
308+
}
309+
}
310+
```
311+
272312
<!-- tabs:end -->
273313

274314
<!-- solution:end -->
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class Solution {
2+
func findOrder(_ numCourses: Int, _ prerequisites: [[Int]]) -> [Int] {
3+
var graph = Array(repeating: [Int](), count: numCourses)
4+
var indegree = Array(repeating: 0, count: numCourses)
5+
6+
for prereq in prerequisites {
7+
let course = prereq[0]
8+
let prereqCourse = prereq[1]
9+
graph[prereqCourse].append(course)
10+
indegree[course] += 1
11+
}
12+
13+
var queue = [Int]()
14+
for i in 0..<numCourses {
15+
if indegree[i] == 0 {
16+
queue.append(i)
17+
}
18+
}
19+
20+
var order = [Int]()
21+
while !queue.isEmpty {
22+
let course = queue.removeFirst()
23+
order.append(course)
24+
25+
for nextCourse in graph[course] {
26+
indegree[nextCourse] -= 1
27+
if indegree[nextCourse] == 0 {
28+
queue.append(nextCourse)
29+
}
30+
}
31+
}
32+
33+
return order.count == numCourses ? order : []
34+
}
35+
}

0 commit comments

Comments
 (0)