Skip to content

Commit aaee62b

Browse files
authored
Merge pull request TheAlgorithms#349 from c-utkarsh/add-floyd-warshall
Added FloydWarshall All Pairs Shortest Path Algo
2 parents 38a5cb2 + 920f4b3 commit aaee62b

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

Graphs/FloydWarshall.js

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff 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()

0 commit comments

Comments
 (0)