This repository was archived by the owner on Nov 26, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathdijkstra.py
More file actions
81 lines (61 loc) · 2.04 KB
/
dijkstra.py
File metadata and controls
81 lines (61 loc) · 2.04 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import queue
from collections import namedtuple
Edge = namedtuple('Edge', ['vertex', 'weight'])
class Graph():
def __init__(self, vertexCount):
self.vertexCount = vertexCount
self.adjacencyList = [[] for _ in range(vertexCount)]
def addEdge(self, source, dest, weight):
assert source < self.vertexCount
assert dest < self.vertexCount
self.adjacencyList[source].append(Edge(dest, weight))
self.adjacencyList[dest].append(Edge(source, weight))
def getEdge(self, vertex):
for e in self.adjacencyList[vertex]:
yield e
def getVertex(self):
for v in range(self.vertexCount):
yield v
def dijkstra(graph, source, dest):
q = queue.PriorityQueue()
parents = []
distances = []
startWeight = float("inf")
for i in graph.getVertex():
weight = startWeight
if source == i:
weight = 0
distances.append(weight)
parents.append(None)
q.put(([0, source]))
while not q.empty():
v_tuple = q.get()
v = v_tuple[1]
for e in graph.getEdge(v):
tempDistance = distances[v] + e.weight
if distances[e.vertex] > tempDistance:
distances[e.vertex] = tempDistance
parents[e.vertex] = v
q.put(([distances[e.vertex], e.vertex]))
path = []
end = dest
while end is not None:
path.append(end)
end = parents[end]
path.reverse()
return path, distances[dest]
def main():
count = int(input("Enter no of vertices = "))
g = Graph(count)
edgeCount = int(input("Enter no of edges = "))
for i in range(0, edgeCount):
src, dest, weight = map(int, input().split())
g.addEdge(src, dest, weight)
src = int(input("Enter source node = "))
dest = int(input("Enter destination node = "))
shortest_path, distance = dijkstra(g, src, dest)
print("Shortest Path : ")
print(shortest_path)
print(f"Shortest Distance = {distance}")
if __name__ == "__main__":
main()