3243. Shortest Distance After Road Addition Queries I #883
-
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to simulate adding roads between cities and calculate the shortest path from city Approach:
Let's implement this solution in PHP: 3243. Shortest Distance After Road Addition Queries I <?php
/**
* @param Integer $n
* @param Integer[][] $queries
* @return Integer[]
*/
function shortestDistanceAfterQueries($n, $queries) {
// Initialize adjacency list for the graph
$graph = array_fill(0, $n, []);
for ($i = 0; $i < $n - 1; $i++) {
$graph[$i][] = $i + 1; // Add the default unidirectional road
}
$result = [];
// Process each query
foreach ($queries as $query) {
list($u, $v) = $query;
$graph[$u][] = $v; // Add the new road
// Calculate the shortest path from 0 to n-1 after adding this road
$result[] = bfs($graph, $n);
}
return $result;
}
/**
* Function to find the shortest path using BFS
*
* @param $graph
* @param $n
* @return int
*/
function bfs($graph, $n) {
$queue = [[0, 0]]; // [current node, distance from source]
$visited = array_fill(0, $n, false);
$visited[0] = true;
while (!empty($queue)) {
list($node, $dist) = array_shift($queue);
if ($node == $n - 1) {
return $dist; // Found the shortest path to city n-1
}
foreach ($graph[$node] as $neighbor) {
if (!$visited[$neighbor]) {
$visited[$neighbor] = true;
$queue[] = [$neighbor, $dist + 1];
}
}
}
return -1; // If there's no path (shouldn't happen in this problem)
}
// Example 1
$n = 5;
$queries = [[2, 4], [0, 2], [0, 4]];
print_r(shortestDistanceAfterQueries($n, $queries));
// Example 2
$n = 4;
$queries = [[0, 3], [0, 2]];
print_r(shortestDistanceAfterQueries($n, $queries));
?> Explanation:
Example Walkthrough:For the input
Thus, the output is Final Thoughts:
|
Beta Was this translation helpful? Give feedback.
We need to simulate adding roads between cities and calculate the shortest path from city
0
to cityn - 1
after each road addition. Given the constraints and the nature of the problem, we can use Breadth-First Search (BFS) for unweighted graphs.Approach:
Graph Representation:
i
will have a road to cityi + 1
for all0 <= i < n - 1
.u_i
tov_i
into the graph.Shortest Path Calculation (BFS):
0
to cityn - 1
. BFS works well here because all roads have equal weight (each road has a length of 1).Iterating…