-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0207-course-schedule.swift
55 lines (43 loc) · 1.44 KB
/
0207-course-schedule.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
47
48
49
50
51
52
53
class Solution {
func canFinish(_ numCourses: Int, _ prerequisites: [[Int]]) -> Bool {
// map each course to prereq List
var preMap = [Int: [Int]]()
for num in 0..<numCourses {
preMap[num] = []
}
for prerequisitePair in prerequisites {
let course = prerequisitePair[0]
let prerequisite = prerequisitePair[1]
preMap[course, default: []] += [prerequisite]
}
// visitSet is all courses along the current DFS path
var visitSet = Set<Int>()
for crs in 0..<numCourses {
let canCompleteCourse = dfs(crs, &preMap, &visitSet)
if !canCompleteCourse {
return false
}
}
return true
}
func dfs(_ crs: Int, _ preMap: inout [Int: [Int]], _ visitSet: inout Set<Int>) -> Bool {
guard !visitSet.contains(crs) else {
return false
}
if preMap[crs] == [] {
return true
}
visitSet.insert(crs)
if let prerequisites = preMap[crs] {
for pre in prerequisites {
let canCompletePrerequisite = dfs(pre, &preMap, &visitSet)
if !canCompletePrerequisite {
return false
}
}
}
visitSet.remove(crs)
preMap[crs] = []
return true
}
}