Error in the implementation of Dijkstra's algorithm

I wrote Dijkstra's algorithm for a directed graph. The essence of this named example is that it finds the most likely successful path (i.e. the probabilities are specified so multiplication is used). The condition for 100 vertices and 9900 arcs does not pass. At the same time, it passes 100 vertices and ~5000 arcs. Apparently something is not taken into account but I can not find what. Maybe someone can tell you from experience? The input looks like this: 1 2 0.5 (start vertex-end vertex-probability) The conclusion is as follows: 1 2 4 6 (the most likely successful path) 0.4444 (the probability of passing the path)

I apologize in advance for my crooked arm.

def Dijkstra(N, S, matrix, end):
    valid = [True] * N
    weight = [0.01] * N
    weight[S] = 1.0
    ves=[0.0]*N
    result=[]
    for i in range(N):
        min_weight = 0.0
        ID_min_weight = 0.0
        for i in range(len(weight)):
            if valid[i] and weight[i] > min_weight:
                min_weight = weight[i]
                ID_min_weight = i
        for i in range(N):
            if (round(weight[ID_min_weight] * matrix[ID_min_weight][i],4) > weight[i] and i<end+1):
                weight[i] = round(weight[ID_min_weight] * matrix[ID_min_weight][i],4)
                ves[i]=matrix[ID_min_weight][i]
        valid[ID_min_weight] = False

    result.append(end + 1)
    i = end
    test = end
    while (i!=0):
        for j in range(end, -1, -1):
            if (ves[i]!=0.0 and round(weight[i] / ves[i],4) == weight[j] and i<=test):
                result.append(j+1)
                test=j
        i -= 1


    result.reverse()
    print (*result)

    return round(weight[end],4)

str=[]
matrix2=[]
for i in input().split():
    str.append(int(i))

N = str[0]   # Количество вершин
M = str[1]   # Количество дуг
begin = str[2]  # Начальная вершина
end = str[3]    # Конечная вершина

matrix = [[float (j) for j in input().split()] for i in range(M)]

for i in matrix:
    if len(i)>3:
        exit()

for i in range(N):
    matrix2.append([])
    for j in range(N):
        matrix2[i].append(0.01)

for i in range(M):
    matrix2[int(matrix[i][0]-1)][int(matrix[i][1]-1)] = matrix[i][2]

print(Dijkstra(N, begin-1, matrix2,end-1))
Author: Harry, 2019-10-17

1 answers

I understood correctly that you don't sum weights, but multiply ? Then you will get nonsense, the algorithm is not designed for this. But if you take the logarithms of the weights (of your probabilities) with a minus sign, remember that

  1. Probabilities do not exceed 1
  2. The sum of the logarithms is the logarithm of the product of the arguments
  3. Conditions for the Dijkstra algorithm

And if you think about it a little, you'll understand what's wrong with the scales

enter a description of the image here

Dijkstra's algorithm will give you what you're looking for...

 1
Author: Harry, 2019-10-18 04:00:27