Approach
Breadth-first search
For Second Minimum Time to Reach Destination, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 43 lines of C++ from the credited upstream file 2045.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 3 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 int secondMinimum(int n, vector<vector<int>>& edges, int time, int change) {4 vector<vector<int>> graph(n + 1);5 queue<pair<int, int>> q{{{1, 0}}};6 7 8 vector<vector<int>> minTime(n + 1, vector<int>(2, INT_MAX));9 minTime[1][0] = 0;10 11 for (const vector<int>& edge : edges) {12 const int u = edge[0];13 const int v = edge[1];14 graph[u].push_back(v);15 graph[v].push_back(u);16 }17 18 while (!q.empty()) {19 const auto [u, prevTime] = q.front();20 q.pop();21 22 23 24 const int numChangeSignal = prevTime / change;25 const int waitTime =26 numChangeSignal % 2 == 0 ? 0 : change - prevTime % change;27 const int newTime = prevTime + waitTime + time;28 for (const int v : graph[u])29 if (newTime < minTime[v][0]) {30 minTime[v][0] = newTime;31 q.emplace(v, newTime);32 } else if (minTime[v][0] < newTime && newTime < minTime[v][1]) {33 if (v == n)34 return newTime;35 minTime[v][1] = newTime;36 q.emplace(v, newTime);37 }38 }39 40 throw;41 }42};43