-
Notifications
You must be signed in to change notification settings - Fork 233
/
dijkstra-algorithm.py
158 lines (134 loc) · 4.61 KB
/
dijkstra-algorithm.py
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# DIJKSTRA'S ALGORITHM
# O(V^2 + E) time and O(V) space, E -> Totsl number of edges
def dijkstrasAlgorithm(start, edges):
# Write your code here.
distances = [float('inf')] * len(edges)
distances[start] = 0
visited = set()
calculateShortestPath(edges, distances, start, visited)
for i, distance in enumerate(distances):
if distance == float('inf'):
distances[i] = -1
return distances
def calculateShortestPath(edges, distances, currentVertex, visited):
visited.add(currentVertex)
for pair in edges[currentVertex]:
destination = pair[0]
distance = pair[1]
pathLength = distances[currentVertex] + distance
distances[destination] = min(distances[destination], pathLength)
nextVertex = findMinDistance(distances, visited)
if nextVertex != -1:
calculateShortestPath(edges, distances, nextVertex, visited)
def findMinDistance(distances, visited):
minDistance = float('inf')
minDistancePos = -1
for i, distance in enumerate(distances):
if i not in visited and distance < minDistance:
minDistance = distance
minDistancePos = i
return minDistancePos
# O(V^2 + E) time and O(V) space, E -> Totsl number of edges
def dijkstrasAlgorithm(start, edges):
# Write your code here.
distances = [float('inf')] * len(edges)
distances[start] = 0
visited = set()
while len(visited) != len(edges):
nextVertex, minDistance = findMinDistance(distances, visited)
if minDistance == float('inf'):
break
visited.add(nextVertex)
for pair in edges[nextVertex]:
destination = pair[0]
distance = pair[1]
pathLength = distances[nextVertex] + distance
distances[destination] = min(distances[destination], pathLength)
for i, distance in enumerate(distances):
if distance == float('inf'):
distances[i] = -1
return distances
def findMinDistance(distances, visited):
minDistance = float('inf')
minDistancePos = -1
for i, distance in enumerate(distances):
if i not in visited and distance < minDistance:
minDistance = distance
minDistancePos = i
return minDistancePos, minDistance
# O((V + E)* log(V)) time and O(V) space, E -> Totsl number of edges
def dijkstrasAlgorithm(start, edges):
# Write your code here.
distances = [float('inf')] * len(edges)
distances[start] = 0
minDistanceHeap = MinHeap([(idx, float('inf')) for idx in range(len(edges))])
minDistanceHeap.update(start, 0)
while not minDistanceHeap.isEmpty():
nextVertex, minDistance = minDistanceHeap.remove()
if minDistance == float('inf'):
break
for pair in edges[nextVertex]:
destination = pair[0]
distance = pair[1]
pathLength = distances[nextVertex] + distance
if pathLength < distances[destination]:
distances[destination] = pathLength
minDistanceHeap.update(destination, pathLength)
for i, distance in enumerate(distances):
if distance == float('inf'):
distances[i] = -1
return distances
class MinHeap:
def __init__(self, array):
# Do not edit the line below.
self.vertexMap = {idx: idx for idx in range(len(array))}
self.heap = self.buildHeap(array)
def isEmpty(self):
return len(self.heap) == 0
# O(N) time and O(1) space
def buildHeap(self, array):
# Write your code here.
firstParent = (len(array) - 2) // 2
for currentIndex in reversed(range(firstParent + 1)):
self.siftDown(currentIndex, len(array) - 1, array)
#print(array)
return array
# O(log(n)) time and O(1) space
def siftDown(self, start, endIdx, heap):
# Write your code here.
childOneIdx = start * 2 + 1
while childOneIdx <= endIdx:
childTwoIdx = start * 2 + 2 if start * 2 + 2 <= endIdx else -1
if childTwoIdx != -1 and heap[childTwoIdx][1] < heap[childOneIdx][1]:
idxToSwap = childTwoIdx
else:
idxToSwap = childOneIdx
if heap[idxToSwap][1] < heap[start][1]:
self.swap(start, idxToSwap, heap)
start = idxToSwap
childOneIdx = start * 2 + 1
else:
return
# O(log(n)) time and O(1) space
def siftUp(self, start, heap):
# Write your code here.
parentIdx = (start - 1) // 2
while start > 0 and heap[start][1] < heap[parentIdx][1]:
self.swap(start, parentIdx, heap)
start = parentIdx
parentIdx = (start - 1) // 2
def swap(self, i, j, array):
self.vertexMap[array[i][0]] = j
self.vertexMap[array[j][0]] = i
array[i], array[j] = array[j], array[i]
# O(log(n)) time and O(1) space
def remove(self):
# Write your code here.
self.swap(0, len(self.heap) - 1, self.heap)
vertex, distance = self.heap.pop()
self.vertexMap.pop(vertex)
self.siftDown(0, len(self.heap) - 1, self.heap)
return vertex, distance
def update(self, vertex, value):
self.heap[self.vertexMap[vertex]] = (vertex, value)
self.siftUp(self.vertexMap[vertex], self.heap)