Skip to content

Commit 28b5d0f

Browse files
committed
Fix Bellman-Ford implementation
1 parent 95f879a commit 28b5d0f

File tree

1 file changed

+13
-7
lines changed

1 file changed

+13
-7
lines changed

src/graphs/shortest-path/bellman-ford.js

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,13 @@
1212
* var Edge = BellmanFord.Edge;
1313
* var bellmanFord = BellmanFord.bellmanFord;
1414
* var edges = [];
15-
* var vertexes = [0, 1, 2, 3, 4];
15+
* var vertexes = [
16+
* new Vertex(0),
17+
* new Vertex(1),
18+
* new Vertex(2),
19+
* new Vertex(3),
20+
* new Vertex(4)
21+
* ];
1622
*
1723
* edges.push(new Edge(0, 1, -1));
1824
* edges.push(new Edge(0, 2, 4));
@@ -55,23 +61,23 @@
5561
var parents = {};
5662
var c;
5763
for (var i = 0; i < vertexes.length; i += 1) {
58-
distances[vertexes[i]] = Infinity;
59-
parents[vertexes[i]] = null;
64+
distances[vertexes[i].id] = Infinity;
65+
parents[vertexes[i].id] = null;
6066
}
6167
distances[source] = 0;
6268
for (i = 0; i < vertexes.length - 1; i += 1) {
6369
for (var j = 0; j < edges.length; j += 1) {
6470
c = edges[j];
65-
if (distances[c.from] + c.weight < distances[c.to]) {
66-
distances[c.to] = distances[c.from] + c.weight;
67-
parents[c.to] = c.from;
71+
if (distances[c.from.id] + c.distance < distances[c.to.id]) {
72+
distances[c.to.id] = distances[c.from.id] + c.distance;
73+
parents[c.to.id] = c.from.id;
6874
}
6975
}
7076
}
7177

7278
for (i = 0; i < edges.length; i += 1) {
7379
c = edges[i];
74-
if (distances[c.from] + c.weight < distances[c.to]) {
80+
if (distances[c.from.id] + c.distance < distances[c.to.id]) {
7581
return undefined;
7682
}
7783
}

0 commit comments

Comments
 (0)