GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — TypeScriptAlgorithms/graph/floyd_warshall.ts at master · categoryx/TypeScriptAlgorithms Expand file tree/ Copy pathfloyd_warshall.tsMore file actions 38 lines (35 loc) · 1.57 KB / Copy pathfloyd_warshall.tsFile metadata and controls38 lines (35 loc) · 1.57 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 /** * @function floydWarshall * @description Compute the shortest path for all pairs of nodes for a graph without negative weight edges. The input graph is a adjacency matrix, where graph[i][j] holds the weight of edges a->b. If the edge does not exist, the value in the matrix is Infinity. * @Complexity_Analysis * Time complexity: O(V^3) * Space Complexity: O(V^2). This space is required to hold the result * @param {number[][]} graph - The graph in adjacency matrix form * @return {number[][]} - A matrix holding the shortest path for each pair of nodes. matrix[i][j] holds the distance of the shortest path (i -> j). * @see https://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm */ export const floydWarshall = (graph: number[][]): number[][] => { let distances = structuredClone(graph) const N = graph.length // We begin by setting the weighted adjacency matrix as the shortest paths. // For the k'th iteration, we try to relax the shortest paths by including node k in the path. for (let k = 0; k < N; ++k) { const newDistances = [] for (let i = 0; i < N; ++i) { newDistances.push(Array(N).fill(Infinity)) } for (let i = 0; i < N; ++i) { for (let j = 0; j < N; ++j) { // The shortest path from node i to j is the minimum of: // 1. the shortest path (i -> j) without node k // 2. the sum of the shortest path (i -> k) and (k -> j) newDistances[i][j] = Math.min( distances[i][j], distances[i][k] + distances[k][j] ) } } distances = newDistances } return distances } |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |