Problem
You are given an undirected weighted graph of n
nodes numbered from 0 to `n
- 1
. The graph consists of
medges represented by a 2D array
edges, where
edges[i] = [ai, bi, wi]indicates that there is an edge between nodes
aiand
biwith weight
wi`.
Consider all the shortest paths from node 0 to node n - 1
in the graph. You need to find a boolean array answer
where answer[i]
is true
if the edge edges[i]
is part of at least one shortest path. Otherwise,
answer[i]
is false
.
Return the array answer
.
Note that the graph may not be connected.
Examples
Example 1
|
|
Example 2
|
|
Constraints
2 <= n <= 5 * 10^4
m == edges.length
1 <= m <= min(5 * 104, n * (n - 1) / 2)
0 <= ai, bi < n
ai != bi
1 <= wi <= 10^5
- There are no repeated edges.
Solution
Method 1 – Dijkstra + Path Backtracking 1
Intuition
To determine if an edge is part of any shortest path from node 0 to node n-1, we can use Dijkstra’s algorithm to find shortest distances, then check for each edge if it can be used in a shortest path by verifying if the sum of distances and edge weight equals the shortest path length.
Approach
- Build the adjacency list from the edge list.
- Run Dijkstra’s algorithm from node 0 to get the shortest distance to all nodes (
dist_from_start
). - Run Dijkstra’s algorithm from node n-1 to get the shortest distance to all nodes (
dist_to_end
). - The shortest path length from 0 to n-1 is
dist_from_start[n-1]
. - For each edge [u, v, w], check if
dist_from_start[u] + w + dist_to_end[v] == shortest
ordist_from_start[v] + w + dist_to_end[u] == shortest
. If so, mark answer[i] as true.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O((n+m)log n)
, due to Dijkstra’s algorithm run twice and edge checks. - 🧺 Space complexity:
O(n+m)
, for graph and distance arrays.