[LeetCode] Second Minimum Time to Reach Destination

2045. Second Minimum Time to Reach Destination

A city is represented as a bi-directional connected graph with n vertices where each vertex is labeled from 1 to n (inclusive). The edges in the graph are represented as a 2D integer array edges, where each edges[i] = [ui, vi] denotes a bi-directional edge between vertex ui and vertex vi. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself. The time taken to traverse any edge is time minutes.

Each vertex has a traffic signal which changes its color from green to red and vice versa every change minutes. All signals change at the same time. You can enter a vertex at any time, but can leave a vertex only when the signal is green. You cannot wait at a vertex if the signal is green.

The second minimum value is defined as the smallest value strictly larger than the minimum value.

  • For example the second minimum value of [2, 3, 4] is 3, and the second minimum value of [2, 2, 4] is 4.

Given n, edges, time, and change, return the second minimum time it will take to go from vertex 1 to vertex n.

Notes:

  • You can go through any vertex any number of times, including 1 and n.
  • You can assume that when the journey starts, all signals have just turned green.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
public:
int secondMinimum(int n, vector<vector<int>>& edges, int time, int change) {
unordered_map<int, vector<int>> m;
vector<pair<int, int>> v(n + 1, {0, 0});
queue<pair<int, int>> q;
for(auto& e : edges) {
m[e[0]].push_back(e[1]);
m[e[1]].push_back(e[0]);
}

q.push({1,0});
v[1] = {1, 0}; // node 1 visited once, at time 0
while(true) {
auto [node, arrive] = q.front();
q.pop();
bool needWait = (arrive / change) & 1; // arrive / change is odd means we have to wait
int waitTime = needWait ? ((arrive / change) + 1) * change - arrive : 0;
int nextTime = arrive + waitTime + time;
for(auto& nxt : m[node]) {
//check how many times next node visited, more than 2 times is not necessary
if(v[nxt].first < 2 and v[nxt].second != nextTime) {
q.push({nxt, arrive + waitTime + time});
v[nxt].first += 1;
v[nxt].second = nextTime;
if(nxt == n and v[nxt].first == 2) {
return nextTime;
}
}
}
}

return -1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/02/PS/LeetCode/second-minimum-time-to-reach-destination/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.