Skip to content

Instantly share code, notes, and snippets.

@m00nlight
Last active June 25, 2022 05:57
Show Gist options
  • Save m00nlight/245d917cb030c515c513 to your computer and use it in GitHub Desktop.
Save m00nlight/245d917cb030c515c513 to your computer and use it in GitHub Desktop.
Python heap optimize dijkstra algorithm
import sys
from heapq import heappush, heappop
class Dijkstra:
def __init__(self, adjacents):
self.adj = adjacents
self.n = len(adjacents)
def dijkstra(self, start):
dis, vis, hq = {}, {}, []
for node in self.adj.keys():
dis[node] = sys.maxint
vis[node] = False
dis[start], vis[start] = 0, True
heappush(hq, (0, start))
while hq:
(d, node) = heappop(hq)
vis[node] = True
for n, weight in self.adj[node].items():
if (not vis[n]) and (d + weight < dis[n]):
dis[n] = d + weight
heappush(hq, (dis[n], n))
return dis
G = {'s':{'u':10, 'x':5},
'u':{'v':1, 'x':2},
'v':{'y':4},
'x':{'u':3, 'v':9, 'y':2},
'y':{'s':7, 'v':6}}
if __name__ == '__main__':
d = Dijkstra(G)
print d.dijkstra('s')
print d.dijkstra('u')
print d.dijkstra('x')
@Parit99
Copy link

Parit99 commented Jun 25, 2022

I guess the time complexity is still VE complete graph it will be V^2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment