-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathfloyd-warshall.js
52 lines (46 loc) · 1.06 KB
/
floyd-warshall.js
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
39
40
41
42
43
44
45
46
47
48
49
50
51
const floydWarshall = graph => {
const dist = []
const { length } = graph
for (let i = 0; i < length; i++) {
dist[i] = []
for (let j = 0; j < length; j++) {
if (i === j) {
dist[i][j] = 0
} else if (!isFinite(graph[i][j])) {
dist[i][j] = Infinity
} else {
dist[i][j] = graph[i][j]
}
}
}
for (let k = 0; k < length; k++) {
for (let i = 0; i < length; i++) {
for (let j = 0; j < length; j++) {
if (dist[i][k] + dist[k][j] < dist[i][j]) {
dist[i][j] = dist[i][k] + dist[k][j]
}
}
}
}
return dist
}
// test
const INF = Infinity
const graph = [
[INF, 2, 4, INF, INF, INF],
[INF, INF, 2, 4, 2, INF],
[INF, INF, INF, INF, 3, INF],
[INF, INF, INF, INF, INF, 2],
[INF, INF, INF, 3, INF, 2],
[INF, INF, INF, INF, INF, INF]
]
const dist = floydWarshall(graph)
let s = ''
for (let i = 0; i < dist.length; ++i) {
s = '';
for (var j = 0; j < dist.length; ++j) {
if (dist[i][j] === INF) s += 'INF ';
else s += dist[i][j] + ' '
}
console.log(s)
}