-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0210-course-schedule-ii.swift
45 lines (42 loc) · 1.1 KB
/
0210-course-schedule-ii.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
/**
* Question Link: https://leetcode.com/problems/course-schedule-ii/
*/
class Solution {
func findOrder(_ numCourses: Int, _ prerequisites: [[Int]]) -> [Int] {
var prereq = [Int: [Int]]()
for i in 0..<numCourses {
prereq[i] = []
}
for p in prerequisites {
let crs = p[0], pre = p[1]
prereq[crs, default: []].append(pre)
}
var output = [Int]()
var visit = Set<Int>()
var cycle = Set<Int>()
func dfs(_ crs: Int) -> Bool {
if cycle.contains(crs) {
return false
}
if visit.contains(crs) {
return true
}
cycle.insert(crs)
for pre in prereq[crs]! {
if !dfs(pre) {
return false
}
}
cycle.remove(crs)
visit.insert(crs)
output.append(crs)
return true
}
for i in 0..<numCourses {
if !dfs(i) {
return []
}
}
return output
}
}