-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdijkstra.py
74 lines (52 loc) · 1.89 KB
/
dijkstra.py
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
import sys
def dijkstra(graph,start,dest):
short_dist = {}
predecessor = {}
unseenNodes = graph
infinity = 9999999
path = []
for item, node in unseenNodes.items():
for cnode, value in node.items():
short_dist[cnode] = infinity
short_dist[start] = 0
while unseenNodes:
minNode = None
for node in unseenNodes:
if minNode is None:
minNode = node
elif short_dist[node] < short_dist[minNode]:
minNode = node
for childNode, weight in graph[minNode].items():
if weight + short_dist[minNode] < short_dist[childNode]:
# print(childNode, weight)
short_dist[childNode] = weight + short_dist[minNode]
predecessor[childNode] = minNode
unseenNodes.pop(minNode)
currentNode = dest
while currentNode != start:
try:
path.insert(0,currentNode)
currentNode = predecessor[currentNode]
except KeyError:
break
path.insert(0,start)
if short_dist[dest] != infinity:
print(' -> '.join(path) + ' : ' + str(short_dist[dest]))
def init_graph():
inputs = list(open(sys.argv[1],"r"))
graph = {}
for i in range(len(inputs)):
graph.update({str(inputs[i].split('\n')[0].split(' ')[0]):{}})
for i in range(len(inputs)):
# print(inputs[i].split('\n')[0].split(' '))
graph[str(inputs[i].split('\n')[0].split(' ')[0])][str(inputs[i].split('\n')[0].split(' ')[1])] = int(inputs[i].split('\n')[0].split(' ')[2])
return graph
try:
graph = init_graph()
print("Graph: \n-------")
print(graph)
print("\nShortest Paths: \n---------------")
dijkstra(init_graph(), sys.argv[2], sys.argv[3])
except:
print("Invalid input, please try again")
print("[USAGE] python dijkstra.py inputs.txt")