-
Notifications
You must be signed in to change notification settings - Fork 80
Expand file tree
/
Copy pathfloydWarshall.js
More file actions
46 lines (36 loc) · 1.35 KB
/
floydWarshall.js
File metadata and controls
46 lines (36 loc) · 1.35 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
39
40
41
42
43
44
45
46
export default function floydWarshall(graph) {
const vertices = graph.getAllVertices();
const nextVertices = Array(vertices.length).fill(null).map(() => {
return Array(vertices.length).fill(null);
});
const distances = Array(vertices.length).fill(null).map(() => {
return Array(vertices.length).fill(Infinity);
});
vertices.forEach((startVertex, startIndex) => {
vertices.forEach((endVertex, endIndex) => {
if (startVertex === endVertex) {
distances[startIndex][endIndex] = 0;
} else {
const edge = graph.findEdge(startVertex, endVertex);
if (edge) {
distances[startIndex][endIndex] = edge.weight;
nextVertices[startIndex][endIndex] = startVertex;
} else {
distances[startIndex][endIndex] = Infinity;
}
}
});
});
vertices.forEach((middleVertex, middleIndex) => {
vertices.forEach((startVertex, startIndex) => {
vertices.forEach((endVertex, endIndex) => {
const distViaMiddle = distances[startIndex][middleIndex] + distances[middleIndex][endIndex];
if (distances[startIndex][endIndex] > distViaMiddle) {
distances[startIndex][endIndex] = distViaMiddle;
nextVertices[startIndex][endIndex] = middleVertex;
}
});
});
});
return { distances, nextVertices };
}