|
| 1 | +/** |
| 2 | + * 1462. Course Schedule IV |
| 3 | + * https://leetcode.com/problems/course-schedule-iv/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. |
| 7 | + * You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you |
| 8 | + * must take course ai first if you want to take course bi. |
| 9 | + * |
| 10 | + * - For example, the pair [0, 1] indicates that you have to take course 0 before you can take |
| 11 | + * course 1. |
| 12 | + * |
| 13 | + * Prerequisites can also be indirect. If course a is a prerequisite of course b, and course b |
| 14 | + * is a prerequisite of course c, then course a is a prerequisite of course c. |
| 15 | + * |
| 16 | + * You are also given an array queries where queries[j] = [uj, vj]. For the jth query, you |
| 17 | + * should answer whether course uj is a prerequisite of course vj or not. |
| 18 | + * |
| 19 | + * Return a boolean array answer, where answer[j] is the answer to the jth query. |
| 20 | + */ |
| 21 | + |
| 22 | +/** |
| 23 | + * @param {number} numCourses |
| 24 | + * @param {number[][]} prerequisites |
| 25 | + * @param {number[][]} queries |
| 26 | + * @return {boolean[]} |
| 27 | + */ |
| 28 | +var checkIfPrerequisite = function(numCourses, prerequisites, queries) { |
| 29 | + const lookup = new Array(numCourses).fill().map(() => new Array(numCourses).fill(false)); |
| 30 | + prerequisites.forEach(([u, v]) => lookup[u][v] = true); |
| 31 | + |
| 32 | + for (let i = 0; i < numCourses; i++) { |
| 33 | + for (let j = 0; j < numCourses; j++) { |
| 34 | + for (let k = 0; k < numCourses; k++) { |
| 35 | + if (lookup[j][i] && lookup[i][k]) { |
| 36 | + lookup[j][k] = true; |
| 37 | + } |
| 38 | + } |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + return queries.map(([u, v]) => lookup[u][v]); |
| 43 | +}; |
0 commit comments