Last active
June 25, 2022 05:57
-
-
Save m00nlight/245d917cb030c515c513 to your computer and use it in GitHub Desktop.
Python heap optimize dijkstra algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I guess the time complexity is still VE complete graph it will be V^2