1027. Bellman-Ford Shortest Path

MediumGraphsShortest PathGraph

Given a directed weighted graph with n nodes and edges [u, v, w] (weights may be negative, but there is no negative cycle), return an array of shortest-path distances from src to every node (use -1 for unreachable). 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,1],[1,2,-2],[2,3,2],[0,3,10]],"src":0}
Output: [0,1,-1,1]
Explanation: Negative edge improves the path to 2.
Example 2
Input: {"n":1,"edges":[],"src":0}
Output: [0]
Explanation: Only the source.
Example 3
Input: {"n":3,"edges":[[0,1,-1],[1,2,-1]],"src":0}
Output: [0,-1,-2]
Explanation: Cumulative negatives.

Constraints

Asked by

AmazonMicrosoftGoogleAdobeFlipkart
Solve this problem in the editor →