Skip to content

Commit 36753c0

Browse files
authored
Merge pull request #1 from dkorduban/dijkstra_e_log_v
Make shortest_path run in O(E log V) instead of O(E^2)
2 parents d5760a1 + f6e5109 commit 36753c0

1 file changed

Lines changed: 13 additions & 18 deletions

File tree

core/pygraph/algorithms/minmax.py

Lines changed: 13 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -208,33 +208,28 @@ def shortest_path(graph, source):
208208
dist = {source: 0}
209209
previous = {source: None}
210210

211-
# This is a sorted queue of (dist, node) 2-tuples. The first item in the
211+
# This is a priority queue of (dist, node) 2-tuples. The first item in the
212212
# queue is always either a finalized node that we can ignore or the node
213213
# with the smallest estimated distance from the source. Note that we will
214214
# not remove nodes from this list as they are finalized; we just ignore them
215215
# when they come up.
216216
q = [(0, source)]
217217

218-
# The set of nodes for which we have final distances.
219-
finished = set()
220-
221-
# Algorithm loop
222218
while len(q) > 0:
223-
du, u = q.pop(0)
224-
225-
# Process reachable, remaining nodes from u
226-
if u not in finished:
227-
finished.add(u)
228-
for v in graph[u]:
229-
if v not in finished:
230-
alt = du + graph.edge_weight((u, v))
231-
if (v not in dist) or (alt < dist[v]):
232-
dist[v] = alt
233-
previous[v] = u
234-
bisect.insort(q, (alt, v))
219+
du, u = heapq.heappop(q)
235220

236-
return previous, dist
221+
# Skip finished node
222+
if dist[u] < du:
223+
continue
224+
225+
for v in graph[u]:
226+
alt = du + graph.edge_weight((u, v))
227+
if (v not in dist) or (alt < dist[v]):
228+
dist[v] = alt
229+
previous[v] = u
230+
heapq.heappush(q, (alt, v))
237231

232+
return previous, dist
238233

239234

240235
def shortest_path_bellman_ford(graph, source):

0 commit comments

Comments
 (0)