| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
1 file changed
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
@@ -0,0 +1,48 @@ | |||
| 1 | + /* | ||
| 2 | + Source: | ||
| 3 | + https://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm | ||
| 4 | + | ||
| 5 | + Complexity: | ||
| 6 | + O(|V|^3) where V is the set of vertices | ||
| 7 | + */ | ||
| 8 | + | ||
| 9 | + const FloydWarshall = (dist) => { | ||
| 10 | + // Input:- dist: 2D Array where dist[i][j] = edge weight b/w i and j | ||
| 11 | + // Output:- dist: 2D Array where dist[i][j] = shortest dist b/w i and j | ||
| 12 | + const n = dist.length | ||
| 13 | + for (let k = 0; k < n; k++) { | ||
| 14 | + for (let i = 0; i < n; i++) { | ||
| 15 | + for (let j = 0; j < n; j++) { | ||
| 16 | + if (dist[i][j] > dist[i][k] + dist[k][j]) { | ||
| 17 | + // dist from i to j via k is lesser than the current distance | ||
| 18 | + dist[i][j] = dist[i][k] + dist[k][j] | ||
| 19 | + } | ||
| 20 | + } | ||
| 21 | + } | ||
| 22 | + } | ||
| 23 | + return dist | ||
| 24 | + } | ||
| 25 | + | ||
| 26 | + const main = () => { | ||
| 27 | + // For the following graph (edge weights are shown in brackets) | ||
| 28 | + // 4 1 dist[1][2] = dist[2][1] = 1 | ||
| 29 | + // \ (2)/ \ dist[1][3] = dist[3][1] = 2 | ||
| 30 | + // \ / \(1) dist[1][4] = dist[4][1] = Infinity | ||
| 31 | + // (1)\ / \ dist[3][4] = dist[4][3] = 1 | ||
| 32 | + // 3 2 dist[2][4] = dist[4][2] = Infinity | ||
| 33 | + // dist[2][3] = dist[3][2] = Infinity | ||
| 34 | + // Output should be: | ||
| 35 | + // [ [0, 1, 2, 3], | ||
| 36 | + // [1, 0, 3, 4], | ||
| 37 | + // [2, 3, 0, 1], | ||
| 38 | + // [3, 4, 1, 0] ] | ||
| 39 | + console.log(FloydWarshall( | ||
| 40 | + [[0, 1, 2, Infinity], | ||
| 41 | + [1, 0, Infinity, Infinity], | ||
| 42 | + [2, Infinity, 0, 1], | ||
| 43 | + [Infinity, Infinity, 1, 0] | ||
| 44 | + ] | ||
| 45 | + )) | ||
| 46 | + } | ||
| 47 | + | ||
| 48 | + main() | ||
| Back | FazBrowse Home | New Git URL |
0 commit comments