改进我的Dijkstras实施?

时间:2016-12-01 20:42:31

标签: python algorithm

我目前正在学习流行的算法,以准备面试。有人能告诉我是否可以改进我的实施?我知道您可以使用二进制堆/优先级队列来将时间复杂度提高到O(E + Vlog(V))并且我的实现是O(V ^ 2),但除此之外,这是否足够或应该我尝试以更加“pythonic”的方式学习它?

g = {
'A':[{'D':2}, {'C':1}],
'B':[{'C':2}, {'F':3}],
'C':[{'A':1}, {'D':1}, {'B':2}, {'E':3}],
'D':[{'C':1}, {'G':1}],
'E':[{'C':3}, {'F':2}],
'F':[{'B':3},{'E':2},{'G':1}],
'G': [{'D':1}, {'F':1}]
}

import math

def dijkstras(graph, start):
#Initiate an empty dictionary for path, and one for the vertices in a graph.
    path, remaining_vertices = {}, {}
#Set values of vertices in graph to infinite
    for vertex in graph:
        remaining_vertices[vertex] = math.inf
#The value of the starting point to itself is always 0.
    remaining_vertices[start] = 0

#Loop until the path has access to all the vertices in a graph
while len(path) < len(graph):
    #variables to select the minimum key/value out of the remaining vertices not yet added into the graph
    min_key = math.inf
    min_weight= math.inf

    #Find minimum value
    for vertex, weight in list(remaining_vertices.items()):
        if weight<min_weight:
            min_weight = weight
            min_key = vertex

    """
    For the vertex to be added into the path, check the values of it's neighbors to see if the path going through
    this vertex is shorter than the currently stored value to that neighbor vertex, if so, overwrite.
    Only for neighbor vertexes that are not already in path.

    min(stored_value, current_vertex_weight + edge_weight_to_neighbor_vertex)
    """

    for neighbors in graph[min_key]:
        for edge, edge_weight in list(neighbors.items()):
            if edge not in path:
                remaining_vertices[edge] = min(remaining_vertices[edge], min_weight+edge_weight)

    #Add our selected vertex and its associated weight to our path dictionary
    path[min_key] = min_weight #Add it to our shortest path

    #Remove it from our selectable vertexes for the next path.
    del remaining_vertices[min_key] #Delete it from our remaining vertices

return path

print(dijkstras(g, 'A'))

0 个答案:

没有答案