Created
March 5, 2019 19:31
-
-
Save qcp/5d3f844abecb1826d623cc80a55753e8 to your computer and use it in GitHub Desktop.
Алгоритм Дейкстры python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-1 -1 -1 15 -1 -1 -1 20 | |
-1 -1 -1 -1 -1 -1 -1 -1 | |
-1 -1 -1 -1 -1 -1 -1 -1 | |
-1 -1 -1 -1 -1 -1 -1 2 | |
-1 -1 -1 -1 -1 -1 -1 -1 | |
-1 -1 -1 -1 -1 -1 -1 -1 | |
-1 -1 -1 -1 -1 -1 -1 -1 | |
-1 -1 -1 -1 -1 -1 -1 -1 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Число которое мы будем считать бесконечностью | |
inf = 1000000 | |
def Dijkstra(N, S, matrix): | |
valid = [True] * N | |
weight = [inf] * N | |
weight[S] = 0 | |
for i in range(N): | |
min_weight = inf+1 | |
ID_min_weight = -1 | |
for j in range(N): | |
if valid[j] and weight[j] < min_weight: | |
min_weight = weight[j] | |
ID_min_weight = j | |
for j in range(N): | |
if weight[ID_min_weight] + matrix[ID_min_weight][j] < weight[j]: | |
weight[j] = weight[ID_min_weight] + matrix[ID_min_weight][j] | |
valid[ID_min_weight] = False | |
return weight | |
def Main(): | |
#начальная вершина | |
start = 0; | |
#файл с матрицей смежности | |
f = open('input.txt') | |
matrix = [list(inf if a<0 else a for a in map(int, row.split())) for row in f.readlines()] | |
for i, item in enumerate(Dijkstra(len(matrix), start, matrix)): | |
if item < inf: print("К вершине {} мы можем дойти за минимальное расстояние {} ".format(i+1, item)) | |
Main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment