Get shortest path.
import bellmanFord from '@algorithm.ts/bellman-ford'
const A = 0
const B = 1
const C = 2
const D = 3
const graph: IGraph = {
N: 4,
source: A,
edges: [
{ to: B, cost: 1 },
{ to: A, cost: -1 },
{ to: C, cost: 0.87 },
{ to: B, cost: -0.87 },
{ to: D, cost: 5 },
{ to: C, cost: -5 },
],
G: [[0], [1, 2], [3, 4], [5]],
}
const noNegativeCycle: boolean = bellmanFord(graph, undefined, context => {
const a2aPath: number[] = context.getShortestPathTo(A)
const a2bPath: number[] = context.getShortestPathTo(B)
const a2cPath: number[] = context.getShortestPathTo(C)
const a2dPath: number[] = context.getShortestPathTo(D)
a2aPath
a2bPath
a2cPath
a2dPath
})
A solution for leetcode "Number of Ways to Arrive at Destination"
(https://leetcode.com/problems/number-of-ways-to-arrive-at-destination/):
import type { IEdge, IGraph } from '@algorithm.ts/bellman-ford'
import bellmanFord from '@algorithm.ts/bellman-ford'
const MOD = 1e9 + 7
export function countPaths(N: number, roads: number[][]): number {
const edges: IEdge[] = []
const G: number[][] = new Array(N)
for (let i = 0; i < N; ++i) G[i] = []
for (const [from, to, cost] of roads) {
G[from].push(edges.length)
edges.push({ to, cost })
G[to].push(edges.length)
edges.push({ to: from, cost })
}
const source = 0
const target = N - 1
const graph: IGraph = { N, source: target, edges, G }
const dist: number[] = customDist ?? []
bellmanFord.bellmanFord(graph, { INF: 1e12, dist })
const dp: number[] = new Array(N).fill(-1)
return dfs(source)
function dfs(o: number): number {
if (o === target) return 1
let answer = dp[o]
if (answer !== -1) return answer
answer = 0
const d = dist[o]
for (const idx of G[o]) {
const e: IEdge = edges[idx]
if (dist[e.to] + e.cost === d) {
const t = dfs(e.to)
answer = modAdd(answer, t)
}
}
return dp[o] = answer
}
}
function modAdd(x: number, y: number): number {
const z: number = x + y
return z < MOD ? z : z - MOD
}