Find the Closest Marked Node - Problem
Imagine you're a delivery driver navigating a city with one-way streets, and you need to find the shortest route to any of your delivery destinations from your current location.
You're given a directed weighted graph representing a city where:
- There are
nintersections (nodes) numbered from0ton-1 - Each edge
[u, v, w]represents a one-way street from intersectionuto intersectionvwith travel timew - You start at intersection
s - You have multiple possible destinations stored in the
markedarray
Your goal: Find the minimum travel time from your starting point s to reach any of the marked destinations. If no destinations are reachable, return -1.
Example: If you're at intersection 0 and need to deliver to intersections [2, 3], find the shortest path to whichever destination is closest.
Input & Output
example_1.py β Basic Graph
$
Input:
n = 4, edges = [[0,1,1],[1,2,2],[0,3,4]], s = 0, marked = [2,3]
βΊ
Output:
3
π‘ Note:
From node 0, we can reach node 2 with distance 1+2=3 (path: 0β1β2) and node 3 with distance 4 (path: 0β3). The minimum distance to any marked node is 3.
example_2.py β No Path Exists
$
Input:
n = 3, edges = [[0,1,2]], s = 0, marked = [2]
βΊ
Output:
-1
π‘ Note:
There is no path from node 0 to node 2, so we return -1.
example_3.py β Source is Marked
$
Input:
n = 4, edges = [[0,1,5],[1,2,3]], s = 0, marked = [0,2]
βΊ
Output:
0
π‘ Note:
The source node 0 is itself marked, so the minimum distance is 0.
Constraints
- 2 β€ n β€ 500
- 1 β€ edges.length β€ 104
- edges[i].length == 3
- 0 β€ ui, vi β€ n-1
- 1 β€ wi β€ 100
- 1 β€ marked.length β€ n
- All marked nodes are distinct
- 0 β€ s β€ n-1
Visualization
Tap to expand
Understanding the Visualization
1
Mark Destinations
Identify all possible destinations (marked nodes) in a set for quick lookup
2
Start Exploration
Begin Dijkstra's algorithm from source, exploring closest nodes first
3
Early Termination
Stop immediately when any marked destination is reached - it's guaranteed to be the closest
Key Takeaway
π― Key Insight: Dijkstra's algorithm explores nodes in order of increasing distance from the source, so the first marked destination encountered is guaranteed to be the globally closest one!
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code