-
Notifications
You must be signed in to change notification settings - Fork 33
/
05) Dijkstra shortest paths.py
102 lines (62 loc) · 1.8 KB
/
05) Dijkstra shortest paths.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
'''
Programming assignment 5:
implement the Dijkstra's
algorithm for computing
shortest paths in a graph.
If there is no path,
define its distance as 1000000.
@author: Mikhail Dubov
'''
def readUndirectedGraph(filename):
adjlist = []
lines = open(filename).read().splitlines()
for line in lines:
adjlist.append([])
data = line.split()
v = int(data[0])-1
for tpl in data[1:]:
ts, ws = tpl.split(',')
t = int(ts)-1
w = int(ws)
adjlist[v].append((t, w))
return adjlist
def extract_min(pq, weights):
i = 0
j = 1
m = weights[pq[0]]
while j < len(pq):
if weights[pq[j]] < m:
i = j
m = weights[pq[j]]
j += 1
res = pq[i]
pq[i] = pq[-1]
pq.pop()
return res
def dijkstraShortestPaths(graph, s):
'''
Works in O(n^2), since we use
an array to maintain the priority queue.
'''
infinity = 1000000
weights = [infinity]*len(graph)
weights[s] = 0
pqueue = [i for i in range(len(graph))]
visited = [False]*len(graph)
while len(pqueue) > 0:
v = extract_min(pqueue, weights)
visited[v] = True
for inc, w in graph[v]:
if not visited[inc]:
weights[inc] = min(weights[inc], weights[v]+w)
return weights
def main():
desired = [7,37,59,82,99,115,133,165,188,197]
graph = readUndirectedGraph('dijkstraData.txt')
weights = dijkstraShortestPaths(graph, 0)
res = []
for i in desired:
res.append(str(weights[i-1]))
print(','.join(res))
if __name__ == '__main__':
main()