Problem Description
Given a directed weighted graph with n nodes (0-indexed) represented by the array edges, where each edge is given as [u, v, w] (an edge from u to v with weight w), and a source node s along with a list of marked nodes, the goal is to determine the minimum distance from s to any of the marked nodes. If no marked node is reachable from the source s, return -1.
Key Insights
- The problem requires computing the shortest path from a source node to a set of target nodes.
- Dijkstra's algorithm is a natural fit since the graph has non-negative edge weights.
- Use a min-heap (or priority queue) to efficiently extract the node with the smallest distance.
- As soon as a marked node is reached, its distance can be considered as a candidate and the minimum among these is desired.
- There is a possibility that some marked nodes may be unreachable, so if none are reachable, return -1.
Space and Time Complexity
Time Complexity: O(E log N) where E is the number of edges and N is the number of nodes, due to the priority queue operations in Dijkstra's algorithm. Space Complexity: O(N + E) for storing the graph and the auxiliary data structures.
Solution
We employ Dijkstra's algorithm to compute the shortest paths from node s to all other nodes in the graph. We begin by constructing the adjacency list from the input edges. A min-heap (or priority queue) is used to repeatedly extract the next node with the minimum known distance. Once a marked node is extracted (or its distance is finalized), its distance can be considered as a candidate. The algorithm iterates until all possible nodes are visited, and finally returns the minimum distance among all encountered marked nodes. If no path to any marked node exists, -1 is returned.