-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdijkstras_algorithm.py
More file actions
57 lines (48 loc) · 1 KB
/
Copy pathdijkstras_algorithm.py
File metadata and controls
57 lines (48 loc) · 1 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
graph = {
'start': {
'a': 6,
'b': 2
},
'a': {
'fin': 1
},
'b': {
'a': 3,
'fin': 5
},
'fin': {}
}
infinity = float('inf')
costs = {
'a': 6,
'b': 2,
'fin': infinity
}
parents = {
'a': 'start',
'b': 'start',
'fin': None
}
processed = []
def find_lowest_cost_node(costs):
lowest_cost = float('inf')
lowest_cost_node = None
for node in costs:
cost = costs[node]
if cost < lowest_cost and node not in processed:
lowest_cost = cost
lowest_cost_node = node
return lowest_cost_node
node = find_lowest_cost_node(costs)
while node is not None:
cost = costs[node]
neighbors = graph[node]
for n in neighbors.keys():
new_cost = cost + neighbors[n]
if costs[n] > new_cost:
costs[n] = new_cost
parents[n] = node
processed.append(node)
node = find_lowest_cost_node(costs)
print "Cost from the start to each node:"
print costs