-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDijikstra's Algorithm.py
More file actions
65 lines (47 loc) · 1.24 KB
/
Dijikstra's Algorithm.py
File metadata and controls
65 lines (47 loc) · 1.24 KB
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
import sys
from collections import defaultdict
import heapq
sys.stdin = open('in.txt', 'r')
sys.stdout = open('out.txt', 'w')
#Code from here
class Solution(object):
def Dijikstra(self,n,e,graph):
"""
Lazy Dijikstra is used. Node and its weight are sorted out
automatically in priority queue.Some nodes are repeated in queue, so
inefficient...But will work in leetcode.
In classic dijikstra we need to pick node with least weight manually.
"""
dist = [100000]*(n+1)
src = 1
dist[src] =0
pq =[] # A priority queue
pq.append((dist[src],src))
heapq.heapify(pq)
while pq:
distvertex , vertex = heapq.heappop(pq)
for node, edgeweight in graph[vertex]:
if(dist[node] > dist[vertex]+edgeweight):
dist[node] =dist[vertex] + edgeweight
heapq.heappush(pq,(dist[node],node))
print(dist[1:])
if __name__ == "__main__":
n, e = map(int, input().split()) # n is no of vertices and e is no of edges d EdgeWeight
graph = defaultdict(list) # adjacency list
for _ in range(e):
v1 ,v2 ,d =map(int,input().split())
graph[v1].append((v2,d))
graph[v2].append((v1,d))
# main(n,e,graph)
a=Solution()
a.Dijikstra(n,e,graph)
"""
Inputs :-
5 6
1 2 2
1 4 1
2 3 4
4 3 3
2 5 5
5 3 1
"""