|
| 1 | +/** |
| 2 | + * 1697. Checking Existence of Edge Length Limited Paths |
| 3 | + * https://leetcode.com/problems/checking-existence-of-edge-length-limited-paths/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * An undirected graph of n nodes is defined by edgeList, where edgeList[i] = [ui, vi, disi] denotes |
| 7 | + * an edge between nodes ui and vi with distance disi. Note that there may be multiple edges between |
| 8 | + * two nodes. |
| 9 | + * |
| 10 | + * Given an array queries, where queries[j] = [pj, qj, limitj], your task is to determine for each |
| 11 | + * queries[j] whether there is a path between pj and qj such that each edge on the path has a |
| 12 | + * distance strictly less than limitj. |
| 13 | + * |
| 14 | + * Return a boolean array answer, where answer.length == queries.length and the jth value of answer |
| 15 | + * is true if there is a path for queries[j] is true, and false otherwise. |
| 16 | + */ |
| 17 | + |
| 18 | +/** |
| 19 | + * @param {number} n |
| 20 | + * @param {number[][]} edgeList |
| 21 | + * @param {number[][]} queries |
| 22 | + * @return {boolean[]} |
| 23 | + */ |
| 24 | +var distanceLimitedPathsExist = function(n, edgeList, queries) { |
| 25 | + const parent = new Array(n).fill().map((_, i) => i); |
| 26 | + |
| 27 | + edgeList.sort((a, b) => a[2] - b[2]); |
| 28 | + const sortedQueries = queries.map((q, i) => [...q, i]).sort((a, b) => a[2] - b[2]); |
| 29 | + const result = new Array(queries.length).fill(false); |
| 30 | + |
| 31 | + let edgeIndex = 0; |
| 32 | + for (const [p, q, limit, index] of sortedQueries) { |
| 33 | + while (edgeIndex < edgeList.length && edgeList[edgeIndex][2] < limit) { |
| 34 | + union(edgeList[edgeIndex][0], edgeList[edgeIndex][1]); |
| 35 | + edgeIndex++; |
| 36 | + } |
| 37 | + result[index] = find(p) === find(q); |
| 38 | + } |
| 39 | + |
| 40 | + return result; |
| 41 | + |
| 42 | + function find(x) { |
| 43 | + if (parent[x] !== x) { |
| 44 | + parent[x] = find(parent[x]); |
| 45 | + } |
| 46 | + return parent[x]; |
| 47 | + } |
| 48 | + |
| 49 | + function union(x, y) { |
| 50 | + parent[find(x)] = find(y); |
| 51 | + } |
| 52 | +}; |
0 commit comments