forked from TheAlgorithms/PHP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBellmanFordTest.php
52 lines (46 loc) · 1.36 KB
/
BellmanFordTest.php
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
52
<?php
require_once __DIR__ . '/../../vendor/autoload.php';
require_once __DIR__ . '/../../Graphs/GraphEdge.php';
require_once __DIR__ . '/../../Graphs/BellmanFord.php';
use PHPUnit\Framework\TestCase;
class BellmanFordTest extends TestCase
{
public function testBellmanFord()
{
$edgesRaw = [
['S', 8, 'E'],
['E', 1, 'D'],
['D', -1, 'C'],
['S', 10, 'A'],
['D', -4, 'A'],
['A', 2, 'C'],
['C', -2, 'B'],
['B', 1, 'A'],
];
$vertices = ['S', 'A', 'B', 'C', 'D', 'E',];
#prepare array of edges listed by edge start to simplify Bellman-Ford updating weights of other edges
$edges = [];
foreach ($edgesRaw as $edgeRaw) {
$edge = new GraphEdge();
$edge->start = $edgeRaw[0];
$edge->end = $edgeRaw[2];
$edge->weight = $edgeRaw[1];
if (!isset($edges[$edgeRaw[0]])) {
$edges[$edgeRaw[0]] = [];
}
$edges[$edgeRaw[0]][] = $edge;
}
$result = bellmanFord($vertices, $edges, 'S');
$this->assertEquals(
[
'S' => 0,
'A' => 5,
'B' => 5,
'C' => 7,
'D' => 9,
'E' => 8
],
$result
);
}
}