-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDijkstraSSSP.py
More file actions
72 lines (57 loc) · 1.9 KB
/
Copy pathDijkstraSSSP.py
File metadata and controls
72 lines (57 loc) · 1.9 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
# Created by Roshan Jayswal
# Copyright © 2021 AppMillers. All rights reserved.
from collections import defaultdict
class Graph:
def __init__(self):
self.nodes = set()
self.edges = defaultdict(list)
self.distances = {}
def addNode(self,value):
self.nodes.add(value)
def addEdge(self, fromNode, toNode, distance):
self.edges[fromNode].append(toNode)
self.distances[(fromNode, toNode)] = distance
def dijkstra(graph, initial):
visited = {initial : 0}
path = defaultdict(list)
nodes = set(graph.nodes)
while nodes:
minNode = None
for node in nodes:
if node in visited:
if minNode is None:
minNode = node
elif visited[node] < visited[minNode]:
minNode = node
if minNode is None:
break
nodes.remove(minNode)
currentWeight = visited[minNode]
for edge in graph.edges[minNode]:
weight = currentWeight + graph.distances[(minNode, edge)]
if edge not in visited or weight < visited[edge]:
visited[edge] = weight
path[edge].append(minNode)
return visited, path
customGraph = Graph()
customGraph.addNode("A")
customGraph.addNode("B")
customGraph.addNode("C")
customGraph.addNode("D")
customGraph.addNode("E")
customGraph.addNode("F")
customGraph.addNode("G")
customGraph.addEdge("A", "B", 2)
customGraph.addEdge("A", "C", 5)
customGraph.addEdge("B", "C", 6)
customGraph.addEdge("B", "D", 1)
customGraph.addEdge("B", "E", 3)
customGraph.addEdge("C", "F", 8)
customGraph.addEdge("D", "E", 4)
customGraph.addEdge("E", "G", 9)
customGraph.addEdge("F", "G", 7)
print(dijkstra(customGraph, "A"))
# See change the distance from d to e to 1 and from b to e to 6.
# then to get to e from a ,
# shortest path should be a b d e
# but your code is giving a b e