Skip to content

Commit e32bc50

Browse files
committed
Dijkstra's Relax Step: Added a check to avoid overflow in calculating edges weights.
1 parent 0910c2d commit e32bc50

File tree

1 file changed

+4
-2
lines changed

1 file changed

+4
-2
lines changed

Algorithms/Graphs/DijkstraShortestPaths.cs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -82,8 +82,10 @@ private void _dijkstra(TGraph graph, TVertex source)
8282
{
8383
var adjacentIndex = _nodesToIndices[edge.Destination];
8484

85-
// calculate a new possible weighted path
86-
var delta = _distances[currentIndex] + edge.Weight;
85+
// calculate a new possible weighted path if the edge weight is less than infinity
86+
var delta = Infinity;
87+
if (edge.Weight < Infinity && (Infinity - edge.Weight) > _distances[currentIndex]) // Handles overflow
88+
delta = _distances[currentIndex] + edge.Weight;
8789

8890
// Relax the edge
8991
// if check is true, a shorter path is found from current to adjacent

0 commit comments

Comments
 (0)