There are a total of numCourses
courses you have to take, labeled from 0
to numCourses - 1
. You are given an array prerequisites
where prerequisites[i] = [ai, bi]
indicates that you must take course ai
first if you want to take course bi
.
- For example, the pair
[0, 1]
indicates that you have to take course0
before you can take course1
.
Prerequisites can also be indirect. If course a
is a prerequisite of course b
, and course b
is a prerequisite of course c
, then course a
is a prerequisite of course c
.
You are also given an array queries
where queries[j] = [uj, vj]
. For the jth
query, you should answer whether course uj
is a prerequisite of course vj
or not.
Return a boolean array answer
, where answer[j]
is the answer to the jth
query.
Example 1:
Input: numCourses = 2, prerequisites = [[1,0]], queries = [[0,1],[1,0]] Output: [false,true] Explanation: The pair [1, 0] indicates that you have to take course 1 before you can take course 0. Course 0 is not a prerequisite of course 1, but the opposite is true.
Example 2:
Input: numCourses = 2, prerequisites = [], queries = [[1,0],[0,1]] Output: [false,false] Explanation: There are no prerequisites, and each course is independent.
Example 3:
Input: numCourses = 3, prerequisites = [[1,2],[1,0],[2,0]], queries = [[1,0],[1,2]] Output: [true,true]
Constraints:
2 <= numCourses <= 100
0 <= prerequisites.length <= (numCourses * (numCourses - 1) / 2)
prerequisites[i].length == 2
0 <= ai, bi <= n - 1
ai != bi
- All the pairs
[ai, bi]
are unique. - The prerequisites graph has no cycles.
1 <= queries.length <= 104
0 <= ui, vi <= n - 1
ui != vi
还是关于课程关系的题,是LeetCode 207. Course Schedule 和LeetCode 210. Course Schedule II 的延续,因此方法也一样,可以用拓扑排序(Topological Sort)来解答。
不同的是,这题问的是任意给定两个课程(c1, c2),课程c2是否要等课程c1修完才能修?我们知道拓扑排序后,所有有关系的课程的先后顺序就定了,相当形成一棵树,对于一个课程,所有需要先修的课程都是该课程的直接的或间接的父节点。如果我们可以把一个课程的所有间接的父节点都转成直接父节点存放在一个集合里,那么查询时就可以立即知道结果。
class Solution:
def checkIfPrerequisite(self, numCourses: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]:
indegree = [0] * numCourses
graph = [[] for i in range(numCourses)]
parent = [set() for i in range(numCourses)]
for (c1, c2) in prerequisites:
graph[c1].append(c2)
parent[c2].add(c1)
indegree[c2] += 1
q = deque()
for i in range(numCourses):
if indegree[i] == 0:
q.append(i)
while q:
c1 = q.popleft()
for c2 in graph[c1]:
for c3 in parent[c1]:
parent[c2].add(c3)
indegree[c2] -= 1
if indegree[c2] == 0:
q.append(c2)
res = []
for (c1, c2) in queries:
if c1 in parent[c2]:
res.append(True)
else:
res.append(False)
return res