-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdeykstra.py
60 lines (52 loc) · 1.21 KB
/
deykstra.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
graph={}
graph["start"]={}
graph["start"]["a"]=6
graph["start"]["b"]=2
graph["a"]={}
graph["a"]["fin"]=1
graph["b"]={}
graph["b"]["a"]=3
graph["b"]["fin"]=5
graph["fin"]={}
infinity = float("inf")
costs = {}
costs["a"]=6
costs["b"]=2
costs["fin"] =infinity
parents = {}
parents["a"] = "start"
parents["b"] = "start"
parents["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)
path=["fin"]
p=parents["fin"]
while p!="start":
path.insert(0, p)
p=parents[p]
#
print("start", end="")
for p in path:
print(f"=>{p}", end="")
path.insert(0, p)
print()
print(f"V={costs['fin']}")