function bellmanFord(V, edges, S) {
const dist = Array(V).fill(Infinity);
dist[S] = 0;
for (let i = 1; i < V; i++) {
for (const [u, v, wt] of edges) {
if (dist[u] !== Infinity && dist[u] + wt < dist[v]) {
dist[v] = dist[u] + wt;
}
}
}
for (const [u, v, wt] of edges) {
if (dist[u] !== Infinity && dist[u] + wt < dist[v]) {
return [-1]; // Negative weight cycle detected
}
}
return dist;
}
const edges1 = [[0,1,5],[0,2,4],[1,3,3],[2,1,6],[3,2,-2]];
console.log("Shortest paths:", bellmanFord(5, edges1, 0));
const edges2 = [[0,1,1],[1,2,-1],[2,0,-1]];
console.log("Cycle detection:", bellmanFord(3, edges2, 0));