forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CourseSchedule.swift
46 lines (38 loc) · 1.33 KB
/
CourseSchedule.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
* Question Link: https://leetcode.com/problems/course-schedule/
* Primary idea: Topological sort, use indegree of a graph and BFS to solve the problem
*
* Time Complexity: O(n), Space Complexity: O(n)
*
*/
class CourseSchedule {
func canFinish(_ numCourses: Int, _ prerequisites: [[Int]]) -> Bool {
var inDegrees = Array(repeating: 0, count: numCourses), fromTo = [Int: [Int]]()
var coursesCouldTake = [Int](), queue = [Int]()
// init graph
for prerequisite in prerequisites {
fromTo[prerequisite[1], default: []].append(prerequisite[0])
inDegrees[prerequisite[0]] += 1
}
// BFS
for course in 0..<numCourses {
if inDegrees[course] == 0 {
queue.append(course)
}
}
while !queue.isEmpty {
let currentCourse = queue.removeFirst()
coursesCouldTake.append(currentCourse)
guard let toCourses = fromTo[currentCourse] else {
continue
}
toCourses.forEach {
inDegrees[$0] -= 1
if inDegrees[$0] == 0 {
queue.append($0)
}
}
}
return coursesCouldTake.count == numCourses
}
}