1028. Shortest Path in DAG (Topo + Relax)

MediumGraphsShortest PathTopological SortGraph

Given a directed acyclic weighted graph with n nodes and edges [u, v, w] (weights may be negative), return the shortest-path distances from src to every node (use -1 for unreachable), computing them by relaxing edges in topological order. The input is JSON {n, edges, src}.

Input: JSON {n, edges, src} with edges [u, v, w].

Output: Array — shortest distance to each node, or -1.

Examples

Example 1
Input: {"n":4,"edges":[[0,1,2],[0,2,5],[1,2,1],[2,3,3]],"src":0}
Output: [0,2,3,6]
Explanation: Relaxing in topo order.
Example 2
Input: {"n":1,"edges":[],"src":0}
Output: [0]
Explanation: Only the source.
Example 3
Input: {"n":3,"edges":[[0,1,-2],[1,2,3]],"src":0}
Output: [0,-2,1]
Explanation: Handles negative weights.

Constraints

Asked by

AmazonMicrosoftGoogleAdobeFlipkart
Solve this problem in the editor →