1462. Course Schedule IV #1232
-
Topics: There are a total of
Prerequisites can also be indirect. If course You are also given an array Return a boolean array Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can use a graph representation and the Floyd-Warshall algorithm to compute whether each course is reachable from another course. This approach will efficiently handle the prerequisite relationships and allow us to answer the queries directly. Let's implement this solution in PHP: 1462. Course Schedule IV <?php
/**
* @param Integer $numCourses
* @param Integer[][] $prerequisites
* @param Integer[][] $queries
* @return Boolean[]
*/
function checkIfPrerequisite($numCourses, $prerequisites, $queries) {
// Step 1: Initialize the graph with false values
$isReachable = array_fill(0, $numCourses, array_fill(0, $numCourses, false));
// Step 2: Fill the graph with direct prerequisites
foreach ($prerequisites as $prerequisite) {
$isReachable[$prerequisite[0]][$prerequisite[1]] = true;
}
// Step 3: Use Floyd-Warshall algorithm to calculate transitive closure
for ($k = 0; $k < $numCourses; $k++) {
for ($i = 0; $i < $numCourses; $i++) {
for ($j = 0; $j < $numCourses; $j++) {
if ($isReachable[$i][$k] && $isReachable[$k][$j]) {
$isReachable[$i][$j] = true;
}
}
}
}
// Step 4: Answer the queries
$result = [];
foreach ($queries as $query) {
$result[] = $isReachable[$query[0]][$query[1]];
}
return $result;
}
// Example usage:
$numCourses = 2;
$prerequisites = [[1,0]];
$queries = [[0,1],[1,0]];
$result = checkIfPrerequisite($numCourses, $prerequisites, $queries);
print_r($result); // Output: [false,true]
$numCourses = 2;
$prerequisites = [];
$queries = [[1,0],[0,1]]
$result = checkIfPrerequisite($numCourses, $prerequisites, $queries);
print_r($result); // Output: [false,false]
$numCourses = 3;
$prerequisites = [[1, 2], [1, 0], [2, 0]];
$queries = [[1, 0], [1, 2]];
$result = checkIfPrerequisite($numCourses, $prerequisites, $queries);
print_r($result); // Output: [true, true]
?> Explanation:
Complexity:
Example Walkthrough:Input:$numCourses = 3;
$prerequisites = [[1, 2], [1, 0], [2, 0]];
$queries = [[1, 0], [1, 2]]; Execution:
Output:[true, true] |
Beta Was this translation helpful? Give feedback.
We can use a graph representation and the Floyd-Warshall algorithm to compute whether each course is reachable from another course. This approach will efficiently handle the prerequisite relationships and allow us to answer the queries directly.
Let's implement this solution in PHP: 1462. Course Schedule IV