2045. Second Minimum Time to Reach Destination #125
-
A city is represented as a bi-directional connected graph with Each vertex has a traffic signal which changes its color from green to red and vice versa every The second minimum value is defined as the smallest value strictly larger than the minimum value.
Given Notes:
Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
To solve this problem, we can follow these steps:
Let's implement this solution in PHP: 2045. Second Minimum Time to Reach Destination <?PHP
/**
* @param Integer $n
* @param Integer[][] $edges
* @param Integer $time
* @param Integer $change
* @return Integer
*/
function secondMinimum($n, $edges, $time, $change) {
$graph = array_fill(0, $n + 1, []);
$queue = [];
$queue[] = [1, 0]; // initial position
// minTime[i][0] := the first minimum time to reach the node i
// minTime[i][1] := the second minimum time to reach the node i
$minTime = array_fill(0, $n + 1, [PHP_INT_MAX, PHP_INT_MAX]);
$minTime[1][0] = 0;
foreach ($edges as $edge) {
$u = $edge[0];
$v = $edge[1];
$graph[$u][] = $v;
$graph[$v][] = $u;
}
while (!empty($queue)) {
[$i, $prevTime] = array_shift($queue);
// Start from green.
// If `numChangeSignal` is odd, now red.
// If `numChangeSignal` is even, now green.
$numChangeSignal = intdiv($prevTime, $change);
$waitTime = $numChangeSignal % 2 === 0 ? 0 : $change - $prevTime % $change;
$newTime = $prevTime + $waitTime + $time;
foreach ($graph[$i] as $j) {
if ($newTime < $minTime[$j][0]) {
$minTime[$j][0] = $newTime;
$queue[] = [$j, $newTime];
} elseif ($minTime[$j][0] < $newTime && $newTime < $minTime[$j][1]) {
if ($j === $n) {
return $newTime;
}
$minTime[$j][1] = $newTime;
$queue[] = [$j, $newTime];
}
}
}
throw new Exception("Unable to find the second minimum time");
}
// Example usage
$solution = new Solution();
$n = 5;
$edges = [[1, 2], [1, 3], [1, 4], [3, 4], [4, 5]];
$time = 3;
$change = 5;
echo $solution->secondMinimum($n, $edges, $time, $change) . "\n"; // Output: 13
$n = 2;
$edges = [[1, 2]];
$time = 3;
$change = 2;
echo $solution->secondMinimum($n, $edges, $time, $change) . "\n"; // Output: 11
?> Explanation:
|
Beta Was this translation helpful? Give feedback.
To solve this problem, we can follow these steps:
Let's implement this solution in PHP: 2045. Second Minimum Time to Reach Destination