Skip to content

Commit 6fb76c3

Browse files
committed
Merge pull request #81 from clue/fix-mbf
Fix Moore-Bellman-Ford for unweighted edges
2 parents da71b7a + b795dda commit 6fb76c3

File tree

3 files changed

+43
-1
lines changed

3 files changed

+43
-1
lines changed

src/ShortestPath/MooreBellmanFord.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ private function bigStep(Edges $edges, array &$totalCostOfCheapestPathTo, array
4343
// New possible costs of this path
4444
$newCost = $totalCostOfCheapestPathTo[$fromVertex->getId()] + $edge->getWeight();
4545
if (is_infinite($newCost)) {
46-
$newCost = $edge->getWeight();
46+
$newCost = $edge->getWeight() + 0;
4747
}
4848

4949
// No path has been found yet

tests/ShortestPath/BaseShortestPathTest.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,24 @@ public function testSeparateGraphsAreNotReachable()
116116
$alg->getEdgesTo($vg2);
117117
}
118118

119+
public function testGraphUnweighted()
120+
{
121+
// 1 -> 2
122+
$graph = new Graph();
123+
$v1 = $graph->createVertex(1);
124+
$v2 = $graph->createVertex(2);
125+
$e1 = $v1->createEdgeTo($v2);
126+
127+
$alg = $this->createAlg($v1);
128+
129+
$expectedWeight = $this->getExpectedWeight(array($e1));
130+
$this->assertEquals($expectedWeight, $alg->getDistance($v2));
131+
$this->assertEquals(array(2 => $expectedWeight), $alg->getDistanceMap());
132+
$this->assertEquals(array($e1), $alg->getEdges()->getVector());
133+
$this->assertEquals(array($e1), $alg->getEdgesTo($v2)->getVector());
134+
$this->assertEquals(array(2), $alg->getVertices()->getIds());
135+
}
136+
119137
public function testGraphTwoComponents()
120138
{
121139
// 1 -[10]-> 2

tests/ShortestPath/MooreBellmanFordTest.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,4 +69,28 @@ public function testLoopNegativeWeightIsCycle()
6969

7070
$cycle = $alg->getCycleNegative();
7171
}
72+
73+
public function testNegativeComponentHasCycle()
74+
{
75+
// 1 -[1]-> 2 3 --[-1]--> 4
76+
// ^ |
77+
// \---[-2]----/
78+
$graph = new Graph();
79+
$v1 = $graph->createVertex(1);
80+
$v2 = $graph->createVertex(2);
81+
$v3 = $graph->createVertex(3);
82+
$v4 = $graph->createVertex(4);
83+
$e1 = $v1->createEdgeTo($v2)->setWeight(1);
84+
$e2 = $v3->createEdgeTo($v4)->setWeight(-1);
85+
$e3 = $v4->createEdgeTo($v3)->setWeight(-2);
86+
87+
// second component has a cycle
88+
$alg = $this->createAlg($v3);
89+
$cycle = $alg->getCycleNegative();
90+
91+
// first component does not have a cycle
92+
$alg = $this->createAlg($v1);
93+
$this->setExpectedException('UnderflowException');
94+
$alg->getCycleNegative();
95+
}
7296
}

0 commit comments

Comments
 (0)