Skip to content

Commit

Permalink
Bellman-Ford code formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
Michal Zarnecki committed May 5, 2024
1 parent e502f58 commit 4661257
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 7 deletions.
7 changes: 4 additions & 3 deletions Graphs/BellmanFord.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<?php

class Edge {
class Edge
{
public $start;
public $end;
public int $weight;
Expand Down Expand Up @@ -36,11 +37,11 @@ function bellmanFord(array $verticesNames, array $edges, string $start, bool $ve
}

foreach ($edges[$vertice] as $edge) {
if ($vertices[$edge->end] > $vertices[$vertice] + $edge->weight ) {
if ($vertices[$edge->end] > $vertices[$vertice] + $edge->weight) {
if ($verbose) {
echo "replace $vertice " . $vertices[$edge->end] . " with " . $vertices[$vertice] + $edge->weight . "\n ";
}
$vertices[$edge->end] = $vertices[$vertice] + $edge->weight;
$vertices[$edge->end] = $vertices[$vertice] + $edge->weight;
$change = true;
}
}
Expand Down
8 changes: 4 additions & 4 deletions tests/Graphs/BellmanFordTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,16 @@ public function testBellmanFord()
['C', -2, 'B'],
['B', 1, 'A'],
];
$vertices = [ 'S', 'A', 'B', 'C', 'D', 'E',];
$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) {
foreach ($edgesRaw as $edgeRaw) {
$edge = new Edge();
$edge->start = $edgeRaw[0];
$edge->end = $edgeRaw[2];
$edge->weight = $edgeRaw[1];
if (! isset($edges[$edgeRaw[0]])) {
if (!isset($edges[$edgeRaw[0]])) {
$edges[$edgeRaw[0]] = [];
}
$edges[$edgeRaw[0]][] = $edge;
Expand All @@ -42,7 +42,7 @@ public function testBellmanFord()
'B' => 5,
'C' => 7,
'D' => 9,
'E'=> 8
'E' => 8
]);
}
}

0 comments on commit 4661257

Please sign in to comment.