Bellman-Ford
bellmanFord(graph, start) returns distances and predecessor vertices and supports negative edge weights. A negative cycle returns Err(AlgorithmError) with code ERR_ALGORITHM_NEGATIVE_CYCLE; propagate it with ? or handle it with match.
| Signature | Returns | Complexity |
|---|---|---|
bellmanFord(adj: [usize, i32][][], start: usize) | Result<[i32[], usize?[]], AlgorithmError> | O(VE) time, O(V) memory |
tyrus
import { AlgorithmError, bellmanFord } from "tyrus:algorithm";
const showPaths = (): Result<void, AlgorithmError> => {
const graph: [usize, i32][][] = [[[1, 2]], [[2, -1]], []];
const result = bellmanFord(graph, 0)?;
print(result[0]); // [0, 2, 1]
return Ok();
};
match (showPaths()) {
Ok(_) => {}
Err(error) => { printError(error.code); // ERR_ALGORITHM_NEGATIVE_CYCLE
}
}Study result
bellmanFordInfo returns every pass and relaxation metric and reports a reachable negative cycle as data, including the first edge that still permits relaxation.
tyrus
interface BellmanFordInfo {
distances: i32[];
predecessors: usize?[];
relaxationCount: usize;
processedVertexCount: usize;
examinedEdgeCount: usize;
passCount: usize;
negativeCycleDetected: boolean;
negativeCycleEdge: [usize, usize, i32]?;
}tyrus
import { BellmanFordInfo, ShortestPathInfo, bellmanFordInfo } from "tyrus:algorithm";
const info: BellmanFordInfo = bellmanFordInfo([[[1, 4], [2, 1]], [[3, 1]], [[1, 2], [3, 5]], []], 0);
print(info.distances); // [0, 3, 1, 4]
print(info.predecessors[3] ?? 99); // 1
print(info.relaxationCount); // 5
print(info.processedVertexCount); // 4
print(info.examinedEdgeCount); // 20
print(info.passCount); // 3
print(info.negativeCycleDetected); // false
const cycleEdge = info.negativeCycleEdge;
print(cycleEdge ? "detected" : "none"); // none