@@ -93,29 +93,30 @@ def dijkstrasAlgorithm(start, edges):
93
93
if distance == float ('inf' ):
94
94
distances [i ] = - 1
95
95
return distances
96
-
96
+
97
97
class MinHeap :
98
- def __init__ (self , array ):
99
- # Do not edit the line below.
98
+
99
+ def __init__ (self , array ):
100
+ # Do not edit the line below.
100
101
self .vertexMap = {idx : idx for idx in range (len (array ))}
101
- self .heap = self .buildHeap (array )
102
-
102
+ self .heap = self .buildHeap (array )
103
+
103
104
def isEmpty (self ):
104
105
return len (self .heap ) == 0
105
106
106
107
# O(N) time and O(1) space
107
- def buildHeap (self , array ):
108
- # Write your code here.
109
- firstParent = (len (array ) - 2 ) // 2
108
+ def buildHeap (self , array ):
109
+ # Write your code here.
110
+ firstParent = (len (array ) - 2 ) // 2
110
111
for currentIndex in reversed (range (firstParent + 1 )):
111
112
self .siftDown (currentIndex , len (array ) - 1 , array )
112
113
#print(array)
113
114
return array
114
115
115
116
# O(log(n)) time and O(1) space
116
- def siftDown (self , start , endIdx , heap ):
117
- # Write your code here.
118
- childOneIdx = start * 2 + 1
117
+ def siftDown (self , start , endIdx , heap ):
118
+ # Write your code here.
119
+ childOneIdx = start * 2 + 1
119
120
while childOneIdx <= endIdx :
120
121
childTwoIdx = start * 2 + 2 if start * 2 + 2 <= endIdx else - 1
121
122
if childTwoIdx != - 1 and heap [childTwoIdx ][1 ] < heap [childOneIdx ][1 ]:
@@ -130,9 +131,9 @@ def siftDown(self, start, endIdx, heap):
130
131
return
131
132
132
133
# O(log(n)) time and O(1) space
133
- def siftUp (self , start , heap ):
134
- # Write your code here.
135
- parentIdx = (start - 1 ) // 2
134
+ def siftUp (self , start , heap ):
135
+ # Write your code here.
136
+ parentIdx = (start - 1 ) // 2
136
137
while start > 0 and heap [start ][1 ] < heap [parentIdx ][1 ]:
137
138
self .swap (start , parentIdx , heap )
138
139
start = parentIdx
@@ -144,10 +145,10 @@ def swap(self, i, j, array):
144
145
array [i ], array [j ] = array [j ], array [i ]
145
146
146
147
# O(log(n)) time and O(1) space
147
- def remove (self ):
148
- # Write your code here.
148
+ def remove (self ):
149
+ # Write your code here.
149
150
self .swap (0 , len (self .heap ) - 1 , self .heap )
150
- vertex , distance = self .heap .pop ()
151
+ vertex , distance = self .heap .pop ()
151
152
self .vertexMap .pop (vertex )
152
153
self .siftDown (0 , len (self .heap ) - 1 , self .heap )
153
154
return vertex , distance
0 commit comments