zoukankan      html  css  js  c++  java
  • 练习 Dijkstra 最短路径算法。

    练习 Dijkstra 最短路径算法。

    #coding: utf-8
    
    # Author: woodfox, Oct 14, 2014
    # http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
    
    """
    Let the node at which we are starting be called the initial node. Let the distance of node Y be the distance from the initial node to Y. Dijkstra's algorithm will assign some initial distance values and will try to improve them step by step.
    
    1. Assign to every node a tentative distance value: set it to zero for our initial node and to infinity for all other nodes.
    
    2. Mark all nodes unvisited. Set the initial node as current. Create a set of the unvisited nodes called the unvisited set consisting of all the nodes.
    
    3. For the current node, consider all of its unvisited neighbors and calculate their tentative distances. Compare the newly calculated tentative distance to the current assigned value and assign the smaller one. For example, if the current node A is marked with a distance of 6, and the edge connecting it with a neighbor B has length 2, then the distance to B (through A) will be 6 + 2 = 8. If B was previously marked with a distance greater than 8 then change it to 8. Otherwise, keep the current value.
    
    4. When we are done considering all of the neighbors of the current node, mark the current node as visited and remove it from the unvisited set. A visited node will never be checked again.
    
    5. If the destination node has been marked visited (when planning a route between two specific nodes) or if the smallest tentative distance among the nodes in the unvisited set is infinity (when planning a complete traversal; occurs when there is no connection between the initial node and remaining unvisited nodes), then stop. The algorithm has finished.
    
    6. Select the unvisited node that is marked with the smallest tentative distance, and set it as the new "current node" then go back to step 3.
    """
    
    vertices = [1, 2, 3, 4, 5, 6]
    
    # element structure is: [node1, node2, cost]
    edges = [[1, 6, 14], [1, 2, 7], [1, 3, 9], [3, 6, 2], [2, 3, 10], [3, 4, 11], [2, 4, 15], [6, 5, 9], [5, 4, 6]]
    
    def get_neighbors(node):
        # key is neighbor's node number, value is cost
        result = {}
        for edge in edges:
            if edge[0] == node:
                other = edge[1]
            elif edge[1] == node:
                other = edge[0]
            else:
                continue
            
            result[other] = edge[2] # cost
        return result
    
    #print(get_neighbors(3))
    #print(get_neighbors(5))
    
    MAX_VALUE = 10000
    
    def shorted_path(start, end):
        unvisited = []
        visited = []
        costs = {}
        #result_path = []
        
        for v in vertices:
            if v == start:
                costs[v] = 0
            else:
                costs[v] = MAX_VALUE
            unvisited.append(v)
        
        #print unvisited
        #print costs
        
        current = start
        #result_path.append(current)
        
        while True:
            neighbors = get_neighbors(current)
            min_cost_of_neighbor = MAX_VALUE
            min_cost_n = None
            
            if len(neighbors.keys()) > 0:
                for n, cost in neighbors.iteritems():
                    if n in visited:
                        continue
                    new_cost = costs[current] + cost
                    if new_cost < costs[n]:
                        costs[n] = new_cost
                    if costs[n] < min_cost_of_neighbor:
                        min_cost_of_neighbor = costs[n]
                        min_cost_n = n
            
            visited.append(current)
            #print visited, unvisited, current, min_cost_n
            unvisited.remove(current)
            
            if min_cost_n != None:
                current = min_cost_n
            
            if end in visited:
                break
        
        #print costs
        return costs[end]
    
    print shorted_path(1, 5)
    

    测试:

    Running “dijkstra_test.py”…
    Python 2.7.8teaser
    Theme:  
    20
    copy output
    Program exited with code #0 after 0.05 seconds.
  • 相关阅读:
    【Python】在控制台输出不同颜色的文字
    【python】如何去掉使用BeautifulSoup读取html出现的警告UserWarning: You provided Unicode markup but also provided a value for from_encoding
    【nodejs】修改了下对股票表进行crud操作的代码
    【nodejs】用express又做了份crud
    day20_day23课堂笔记
    Myeclipse中java web.xml报错cvc-complex-type.2.3: Element 'web-app' cannot have character [children], because the type's content type is element- only.
    html中让input标签只读不可编辑的方法
    Win10锁屏壁纸位置在哪? 默认锁屏壁纸怎么提取?
    Potplayer怎么实现视频的镜面翻转?
    How to export Excel files in a Python/Django application
  • 原文地址:https://www.cnblogs.com/thomas888/p/dijkstra.html
Copyright © 2011-2022 走看看