Problem
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:
1 | Input: numCourses = 2, prerequisites = [[1,0]], queries = [[0,1],[1,0]] |
Example 2:
1 | Input: numCourses = 2, prerequisites = [], queries = [[1,0],[0,1]] |
Example 3:
1 | Input: numCourses = 3, prerequisites = [[1,2],[1,0],[2,0]], queries = [[1,0],[1,2]] |
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
Analysis
这是课程表系列题的第4题,背景还是一样的,不同的是prerequisite的关系是有传递性的,同时题目还给出了queries
,每个query[i, j]
查询i
是否j
的prerequisite。对于这种query类型的题目,我们的处理思路一般是求解出所有的答案,然后直接返回,一般是求解出一个矩阵便于快速访问。这里就需要求解出isReach[i][j]
代表i
是否j
的prerequisite。我们以每个节点作为BFS的起点都走一遍,就能构造出isReach
了。
Solution
无。
Code
1 | class Solution { |
Summary
这道题目就是多次BFS,没有特别的难点,主要是根据queries
这种题目特点确定出要计算出一个isReach
二维数组。这道题目的分享到这里,感谢你的支持!