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.
Examples
Example 1:
graph LR; 1 --> 0
|
|
Example 2:
|
|
Example 3:
graph LR; 1 --> 0 1 --> 2 2 --> 0
|
|
Constraints:
2 <= numCourses <= 100
0 <= prerequisites.length <= (numCourses * (numCourses - 1) / 2)
prerequisites[i].length == 2
0 <= ai, bi <= numCourses - 1
ai != bi
- All the pairs
[ai, bi]
are unique. - The prerequisites graph has no cycles.
1 <= queries.length <= 104
0 <= ui, vi <= numCourses - 1
ui != vi
Solution
Method 1 - Floyd Warshall Algorithm
Here is the approach:
- Graph Representation: Represent the courses and their prerequisites as a directed graph where an edge from node
a
to nodeb
(a -> b
) means coursea
is a prerequisite for courseb
. - Prerequisite Checking: To check if a course is a prerequisite of another, use the Floyd-Warshall algorithm which computes the transitive closure of the graph. The result of this algorithm can answer any query about the prerequisites between courses.
- Algorithm:
- Create a matrix
reachable
wherereachable[i][j]
isTrue
if coursei
is a prerequisite of coursej
. - Initialize the matrix: set
reachable[a][b]
toTrue
for every prerequisite pair[a, b]
. - Use the Floyd-Warshall algorithm to compute the transitive closure, updating
reachable[i][j]
toTrue
if there exists a coursek
such thatreachable[i][k]
andreachable[k][j]
are bothTrue
. - For each query
[u, v]
, check the value ofreachable[u][v]
to determine ifu
is a prerequisite ofv
.
- Create a matrix
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(NNNXXXNNN)
- 🧺 Space complexity:
O(NNNXXX)