1462. Course Schedule IV
Difficulty: Medium
Topics: Depth-First Search, Breadth-First Search, Graph, Topological Sort
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.
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:
Example 2:
Example 3:
Constraints:
Hint:
Solution:
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) { ... ... ... /** * go to ./solution.php */ } // 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] ?>
Graph Initialization:
Direct Prerequisites:
Floyd-Warshall Algorithm:
Query Evaluation:
$numCourses = 3; $prerequisites = [[1, 2], [1, 0], [2, 0]]; $queries = [[1, 0], [1, 2]];
$isReachable = [ [false, false, false], [false, false, true], [false, false, false] ];
$isReachable = [ [false, false, false], [true, false, true], [true, false, false] ];
[true, true]
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
The above is the detailed content of Course Schedule IV. For more information, please follow other related articles on the PHP Chinese website!