Skip to content

Commit 6f12355

Browse files
authored
Update 2045-second-minimum-time-to-reach-destination.js
1 parent c6c5b8f commit 6f12355

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

2045-second-minimum-time-to-reach-destination.js

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,3 +49,46 @@ const secondMinimum = (n, edges, time, change) => {
4949
}
5050
return cost[n][1]
5151
}
52+
53+
// another
54+
55+
/**
56+
* @param {number} n
57+
* @param {number[][]} edges
58+
* @param {number} time
59+
* @param {number} change
60+
* @return {number}
61+
*/
62+
var secondMinimum = function (n, edges, time, change) {
63+
const graph = new Map()
64+
for (let i = 1; i <= n; i++) graph.set(i, [])
65+
for (const [u, v] of edges) {
66+
graph.get(u).push(v)
67+
graph.get(v).push(u)
68+
}
69+
const first = Array(n + 1).fill(Infinity)
70+
const second = Array(n + 1).fill(Infinity)
71+
first[1] = 0
72+
73+
const q = new MinPriorityQueue()
74+
q.enqueue(1, 0)
75+
76+
while (q.size()) {
77+
let {element: node, priority: cur} = q.dequeue()
78+
cur += time // cur: arrival time
79+
let leave = cur
80+
if (~~(cur / change) & 1) leave += change - (cur % change)
81+
for (let nei of graph.get(node)) {
82+
if (second[nei] <= cur) continue
83+
if (first[nei] === cur) continue
84+
if (first[nei] > cur) {
85+
second[nei] = first[nei]
86+
first[nei] = cur
87+
} else {
88+
second[nei] = cur
89+
}
90+
q.enqueue(nei, leave)
91+
}
92+
}
93+
return second[n]
94+
}

0 commit comments

Comments
 (0)