-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdij.py
More file actions
36 lines (32 loc) · 1.01 KB
/
dij.py
File metadata and controls
36 lines (32 loc) · 1.01 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
g = [
[0, 0, 1, 1, 9, 0, 0, 0],
[0, 0, 9, 4, 0, 0, 5, 0],
[0, 9, 0, 0, 3, 0, 6, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 5, 0],
[0, 0, 7, 0, 8, 1, 0, 0],
[0, 0, 0, 0, 0, 1, 2, 0],
]
def dijkstra(graph, start):
length = len(graph)
is_visited = [False] * length
cost = [float('inf')] * length
parent = [-1] * length
cost[start] = 0
min_cost = 0
while min_cost < float('inf'):
is_visited[start] = True
for i, vertex in enumerate(graph[start]):
if vertex != 0 and not is_visited[i]:
if cost[i] > vertex + cost[start]:
cost[i] = vertex + cost[start]
parent[i] = start
min_cost = float('inf')
for i in range(length):
if min_cost > cost[i] and not is_visited[i]:
min_cost = cost[i]
start = i
return cost
s = int(input("С какой вершины начать путь? "))
print(dijkstra(g, s))