-
Notifications
You must be signed in to change notification settings - Fork 0
/
bellman-ford.ps1
79 lines (42 loc) · 1.74 KB
/
bellman-ford.ps1
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
function bellman-ford {
param (
$GRAPH
)
##get distances,previousvertex
$distances = @{}
$previousVertices =@{}
$startVertex = $graph.getVertexByKey("O")
# Init all distances with infinity assuming that currently we can't reach
# any of the vertices except start one.
$distances[$startVertex.getKey()] = 0
foreach ($vertex in $graph.getAllVertices()) {
$previousVertices[$vertex.getKEY()] = $null
if ($vertex.getKey() -ne $startVertex.getKey()) {
$distances[$vertex.getKey()] = @{weight =[double]::PositiveInfinity}
}
}
for ($iteration = 0; $iteration -lt ($graph.getAllVertices().count - 1); $iteration += 1) {
$distancesKeys = $distances.Keys
try {
foreach($vertexkey in $distancesKeys){
$vertex = $graph.getVertexByKey($vertexKey)
#go through all edges
foreach ($neighbor in $graph.getneighbors($vertex) ) {
$edge = $graph.findEdge($vertex, $neighbor)
# Find out if the distance to the neighbor is shorter in this iteration
# then in previous one.
$distanceToNeighbor =$distanceToVertex + $edge.weight.weight
$Neighbordistance = ($distances[$neighbor.getkey()] ).weight
if ($distanceToNeighbor -lt $Neighbordistance ) {
$distances[$neighbor.getkey()] = $edge.weight
$previousVertices[$neighbor.getKEY()] = $vertex
s }
}
}
}
catch {
}
}
$endvertex = $GRAPH.getVertexByKey("p")
return $distances, $previousVertices
}