Leetcode 2045 Second Minimum Time to Reach Destination

Problem: Second Minimum Time to Reach Destination

Description

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 ).

Example

Input:

n = 5
edges = [[1, 2], [1, 3], [1, 4], [3, 4], [4, 5]]
time = 3
change = 5

Output:

13

Explanation:

  • Minimum time path: 1 -> 4 -> 5 with time = 6 minutes.
  • Second minimum time path: 1 -> 3 -> 4 -> 5 with time = 13 minutes.

Solution

from collections import deque
from typing import List

class Solution:
    def secondMinimum(self, n: int, edges: List[List[int]], time: int, change: int) -> int:
        # Create the graph as an adjacency list
        g = [[] for _ in range(n + 1)]
        for u, v in edges:
            g[u].append(v)
            g[v].append(u)
        
        # Initialize the queue for BFS
        q = deque([(1, 1)])  # (node, frequency)
        
        # Initialize distances for the shortest and second shortest times
        dist1 = [-1] * (n + 1)
        dist2 = [-1] * (n + 1)
        dist1[1] = 0
        
        # Perform BFS
        while q:
            x, freq = q.popleft()
            t = dist1[x] if freq == 1 else dist2[x]

            # Adjust the time based on the traffic signal
            if (t // change) % 2:
                t = change * (t // change + 1) + time
            else:
                t += time
            
            # Explore neighbors
            for y in g[x]:
                if dist1[y] == -1:
                    dist1[y] = t
                    q.append((y, 1))
                elif dist2[y] == -1 and dist1[y] != t:
                    if y == n:
                        return t
                    dist2[y] = t
                    q.append((y, 2))
        
        return 0

Questions and Answers

1. The Method of Constructing a Graph in This Code

The graph is constructed using an adjacency list. The list g is initialized with empty lists for each vertex. Then, for each edge [u, v] in edges, vertex v is added to the list of neighbors for vertex u, and vertex u is added to the list of neighbors for vertex v.

g = [[] for _ in range(n + 1)]
for u, v in edges:
    g[u].append(v)
    g[v].append(u)
2. How to Use a Queue in deque

A deque (double-ended queue) is used to perform BFS. Nodes are appended to the right end of the deque and popped from the left end. This ensures that nodes are processed in the order they are added, maintaining the BFS order.

q = deque([(1, 1)])  # (node, frequency)
...
q.append((y, freq))
...
x, freq = q.popleft()
3. The Usage of freq in This Code

The freq variable indicates whether the current node’s time is being considered for the first shortest time (freq=1) or the second shortest time (freq=2). This distinction helps in tracking and updating the shortest and second shortest times separately.

4. The Mathematical Equation of Adjusting the Time Based on the Traffic Signal

The time is adjusted based on the traffic signal state. If the current time (t) divided by the signal change interval (change) is odd ((t // change) % 2 == 1), it means we arrive during a red signal, and we need to wait until the next green signal. The adjusted time is calculated as follows:

  • If arriving during a red signal:
    t = ( ( t change + 1 ) × change ) + time t = \left( \left( \frac{t}{\text{change}} + 1 \right) \times \text{change} \right) + \text{time} t=((changet+1)×change)+time
  • Otherwise, add the travel time directly:
    t + = time t += \text{time} t+=time
if (t // change) % 2:
    t = change * (t // change + 1) + time
else:
    t += time
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值