Bellman-Ford
bellmanFord(graph, start) retorna distâncias e predecessores e aceita pesos negativos. Um ciclo negativo retorna Err(AlgorithmError) com o código ERR_ALGORITHM_NEGATIVE_CYCLE; propague-o com ? ou trate-o com match.
| Assinatura | Retorna | Complexidade |
|---|---|---|
bellmanFord(adj: [usize, i32][][], start: usize) | Result<[i32[], usize?[]], AlgorithmError> | tempo O(VE), memória O(V) |
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
}
}Resultado de estudo
bellmanFordInfo retorna as métricas de todas as passagens e relaxações e relata um ciclo negativo alcançável como dado, incluindo a primeira aresta que ainda permite relaxação.
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