Skip to content

add dijkstra MATRIX implementation #1

@leonardoleanodev

Description

@leonardoleanodev
# where i is the vertex, and j de related vertex, value is the distance between than where -1 is infinite 
graph_matrix = [
    [0,10,5,-1,-1,-1], # 0
    [-1,0,-1,1,-1,-1], # 1
    [-1,3,0,8,2,-1],   # 2
    [-1,-1,-1,0,4,5],  # 3
    [-1,-1,-1,-1,0,6], # 4
    [-1,-1,-1,-1,-1,0] # 5
               ]

def find_minor_positive(some_list):
    return min([n for n in some_list  if n>0])

def dijkstra_solve_graph_matrix(graph_matrix):
    # graph_matrix must be a square matrix
    matrix_length = len(graph_matrix) #
    target_index =  len(graph_matrix)-1
    
    path_list = []
    path_distance = 0
    curent_vertex = 0
    iterations = 0
    while curent_vertex != target_index:
        path_list.append(curent_vertex)
        minor_positive_distance = find_minor_positive(graph_matrix[curent_vertex])
        minor_positive_distance_index = graph_matrix[curent_vertex].index(minor_positive_distance)
        curent_vertex = minor_positive_distance_index
        path_distance += minor_positive_distance
        iterations += 1
        if iterations > matrix_length:
            raise Exception("Can not find path by djkstra")
    path_list.append(curent_vertex)
    return path_list, path_distance
print(dijkstra_solve_graph_matrix(graph_matrix))

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions