-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
1462-course-schedule-iv.swift
43 lines (35 loc) · 1.06 KB
/
1462-course-schedule-iv.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
/**
* Question Link: https://leetcode.com/problems/course-schedule-iv/
*/
class Solution {
func checkIfPrerequisite(_ numCourses: Int, _ prerequisites: [[Int]], _ queries: [[Int]]) -> [Bool] {
var adj = [Int: [Int]]()
for i in 0..<numCourses {
adj[i] = []
}
for p in prerequisites {
let prereq = p[0], crs = p[1]
adj[crs, default: []].append(prereq)
}
var prereqMap = [Int: Set<Int>]()
func dfs(_ crs: Int) -> Set<Int> {
if prereqMap[crs] == nil {
prereqMap[crs] = Set<Int>()
for pre in adj[crs]! {
prereqMap[crs]!.formUnion(dfs(pre))
}
}
prereqMap[crs]?.insert(crs)
return prereqMap[crs]!
}
for crs in 0..<numCourses {
dfs(crs)
}
var res = [Bool]()
for q in queries {
let u = q[0], v = q[1]
res.append(prereqMap[v]?.contains(u) ?? false)
}
return res
}
}