|
| 1 | +/** |
| 2 | + * 2045. Second Minimum Time to Reach Destination |
| 3 | + * https://leetcode.com/problems/second-minimum-time-to-reach-destination/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * A city is represented as a bi-directional connected graph with n vertices where each vertex |
| 7 | + * is labeled from 1 to n (inclusive). The edges in the graph are represented as a 2D integer |
| 8 | + * array edges, where each edges[i] = [ui, vi] denotes a bi-directional edge between vertex |
| 9 | + * ui and vertex vi. Every vertex pair is connected by at most one edge, and no vertex has |
| 10 | + * an edge to itself. The time taken to traverse any edge is time minutes. |
| 11 | + * |
| 12 | + * Each vertex has a traffic signal which changes its color from green to red and vice versa |
| 13 | + * every change minutes. All signals change at the same time. You can enter a vertex at any |
| 14 | + * time, but can leave a vertex only when the signal is green. You cannot wait at a vertex |
| 15 | + * if the signal is green. |
| 16 | + * |
| 17 | + * The second minimum value is defined as the smallest value strictly larger than the minimum value. |
| 18 | + * - For example the second minimum value of [2, 3, 4] is 3, and the second minimum value of |
| 19 | + * [2, 2, 4] is 4. |
| 20 | + * |
| 21 | + * Given n, edges, time, and change, return the second minimum time it will take to go from |
| 22 | + * vertex 1 to vertex n. |
| 23 | + */ |
| 24 | + |
| 25 | +/** |
| 26 | + * @param {number} n |
| 27 | + * @param {number[][]} edges |
| 28 | + * @param {number} time |
| 29 | + * @param {number} change |
| 30 | + * @return {number} |
| 31 | + */ |
| 32 | +var secondMinimum = function(n, edges, time, change) { |
| 33 | + const adjList = Array.from({ length: n + 1 }, () => []); |
| 34 | + for (const [u, v] of edges) { |
| 35 | + adjList[u].push(v); |
| 36 | + adjList[v].push(u); |
| 37 | + } |
| 38 | + |
| 39 | + const distances = Array.from({ length: n + 1 }, () => [Infinity, Infinity]); |
| 40 | + const queue = [[1, 0]]; |
| 41 | + distances[1][0] = 0; |
| 42 | + |
| 43 | + while (queue.length) { |
| 44 | + const [node, currTime] = queue.shift(); |
| 45 | + |
| 46 | + for (const next of adjList[node]) { |
| 47 | + const signalCycle = Math.floor(currTime / change); |
| 48 | + const isGreen = signalCycle % 2 === 0; |
| 49 | + let nextTime = currTime + time; |
| 50 | + |
| 51 | + if (!isGreen) { |
| 52 | + nextTime = (signalCycle + 1) * change + time; |
| 53 | + } |
| 54 | + |
| 55 | + if (nextTime < distances[next][0]) { |
| 56 | + distances[next][1] = distances[next][0]; |
| 57 | + distances[next][0] = nextTime; |
| 58 | + queue.push([next, nextTime]); |
| 59 | + } else if (nextTime > distances[next][0] && nextTime < distances[next][1]) { |
| 60 | + distances[next][1] = nextTime; |
| 61 | + queue.push([next, nextTime]); |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + return distances[n][1]; |
| 67 | +}; |
0 commit comments