Problem Description
Given an undirected connected graph with n vertices (labeled 1 through n) and a list of edges, every edge taking a constant time to traverse, determine the second minimum time required to travel from vertex 1 to vertex n. Each vertex contains a traffic signal that alternates between green and red every "change" minutes (all vertices change simultaneously). You can arrive at any time, but you can only leave a vertex when its signal is green, meaning you may have to wait if the signal shows red. The second minimum time is the smallest arrival time that is strictly larger than the minimum.
Key Insights
- We can model the problem as a “shortest path” variant in which we need to track two distinct arrival times at each vertex: the minimum and the second minimum.
- A modified BFS or Dijkstra's algorithm with extra state is used, where for every vertex we store up to two best arrival times.
- When moving from one vertex to another, consider potential waiting time due to the traffic signal cycle. If the current time falls in a red phase (i.e. an odd cycle), compute the waiting time until the next green phase.
- Ensure that if a newly computed time is equal to an already recorded best time for that vertex, then it is skipped because we need strictly larger distinct time values.
Space and Time Complexity
Time Complexity: O(m log n) – Each state (up to 2 per vertex) is pushed/popped from the priority queue, where m is the number of edges. Space Complexity: O(n + m) – For storing the graph and the best arrival times for each vertex.
Solution
We solve the problem using a priority queue (min-heap) augmented BFS/Dijkstra approach. For each vertex, we maintain a list of up to two distinct arrival times. When expanding a state (current time and vertex), we calculate the effective time to leave based on the traffic signal cycle:
- If the current time modulo (2 * change) falls in a red phase (i.e., an odd phase), compute the additional wait time.
- Add the traversal time to get the new arrival time at the adjacent vertex. We update the list of arrival times for that vertex only if the new time is not already recorded and if we have less than two times stored or the new time is smaller than the highest currently stored time. The answer is the second distinct arrival time for vertex n.