Dijkstra's algorithm in python

后端 未结 11 1417
无人及你
无人及你 2021-02-01 09:32

I am trying to implement Dijkstra\'s algorithm in python using arrays. This is my implementation.

def extract(Q, w):
    m=0
    minimum=w[0]
    for i in range(l         


        
11条回答
  •  隐瞒了意图╮
    2021-02-01 09:53

    I broke down the wikipedia description into the following pseudo-code on my blog rebrained.com:

    Initial state:

    1. give nodes two properties - node.visited and node.distance
    2. set node.distance = infinity for all nodes except set start node to zero
    3. set node.visited = false for all nodes
    4. set current node = start node.

    Current node loop:

    1. if current node = end node, finish and return current.distance & path
    2. for all unvisited neighbors, calc their tentative distance (current.distance + edge to neighbor).
    3. if tentative distance < neighbor's set distance, overwrite it.
    4. set current.isvisited = true.
    5. set current = remaining unvisited node with smallest node.distance

    http://rebrained.com/?p=392

    import sys
    def shortestpath(graph,start,end,visited=[],distances={},predecessors={}):
        """Find the shortest path btw start & end nodes in a graph"""
        # detect if first time through, set current distance to zero
        if not visited: distances[start]=0
        # if we've found our end node, find the path to it, and return
        if start==end:
            path=[]
            while end != None:
                path.append(end)
                end=predecessors.get(end,None)
            return distances[start], path[::-1]
        # process neighbors as per algorithm, keep track of predecessors
        for neighbor in graph[start]:
            if neighbor not in visited:
                neighbordist = distances.get(neighbor,sys.maxint)
                tentativedist = distances[start] + graph[start][neighbor]
                if tentativedist < neighbordist:
                    distances[neighbor] = tentativedist
                    predecessors[neighbor]=start
        # neighbors processed, now mark the current node as visited 
        visited.append(start)
        # finds the closest unvisited node to the start 
        unvisiteds = dict((k, distances.get(k,sys.maxint)) for k in graph if k not in visited)
        closestnode = min(unvisiteds, key=unvisiteds.get)
        # now take the closest node and recurse, making it current 
        return shortestpath(graph,closestnode,end,visited,distances,predecessors)
    if __name__ == "__main__":
        graph = {'a': {'w': 14, 'x': 7, 'y': 9},
                'b': {'w': 9, 'z': 6},
                'w': {'a': 14, 'b': 9, 'y': 2},
                'x': {'a': 7, 'y': 10, 'z': 15},
                'y': {'a': 9, 'w': 2, 'x': 10, 'z': 11},
                'z': {'b': 6, 'x': 15, 'y': 11}}
        print shortestpath(graph,'a','a')
        print shortestpath(graph,'a','b')
        """
        Expected Result:
            (0, ['a']) 
            (20, ['a', 'y', 'w', 'b'])
            """
    

提交回复
热议问题