图数据结构_Dijkstra算法


图数据结构Dijkstra算法可以找出最便宜的飞机航线、最近的汽车路线。适用于地图软件和GPS技术

下面以找出最便宜的飞机航线为例:

class City:
    def __init__(self, name):
        self.name = name
        # 把表示邻接点的列表换成字典
        self.routes = {}

    def add_route(self, city, price_info):
        self.routes[city] = price_info

    def dijkstra(self, starting_city, other_cities):
        # 字典routes_from_city用来保存从给定城市(这里是atlanta)到其他所有城市的价格以及途径的城市
        # routes_from_city = {}
        # routes_from_city格式: {终点城市:[价格,到达终点城市所要经过的前一个城市]}
        # 字典最后会是: {atlanta:[0,None], boston:[100, atlanta], chicago:[200, denver], el_paso:[280, chicago]}
        # 从起点城市到起点城市时免费的
        # routes_from_city[starting_city] = [0, starting_city]
        routes_from_city = {starting_city: [0, None]}

        # 初始化该字典,因为去往所有其他城市的花费都未知,所以先设为无限大
        for city in other_cities:
            routes_from_city[city] = [float('inf'), None]
            # 该字典初始会是: {atlanta:[0, None],
            #                 boston:[float('inf'), None],
            #                 chicago:[float('inf'), None],
            #                 denver:[float('inf'), None],
            #                 el_paso:[float('inf'), None]}

        # 记录已经访问的城市的列表
        visited_cities = []

        # 一开始先访问起点城市, 将current_city设为它
        current_city = starting_city

        # 循环访问每一个城市
        while current_city:
            # 正式访问当前城市
            visited_cities.append(current_city)
            # 检查从当前城市触发的每条航线
            for city, price_info in current_city.routes.items():
                # 如果起点城市到其他城市的价格比routes_from_city所记录的更低,则更新记录
                if routes_from_city[city][0] > price_info + routes_from_city[current_city][0]:
                    routes_from_city[city] = [price_info+routes_from_city[current_city][0], current_city]

            # 决定下一个要访问的城市
            current_city = None
            cheapest_route_from_current_city = float('inf')

            # 检查所有已记录的路线
            for city, price_info in routes_from_city.items():
                # 在未访问的城市中找出最便宜的那个,设为下一个要访问的城市
                if price_info[0] < cheapest_route_from_current_city and city not in visited_cities:
                    cheapest_route_from_current_city = price_info[0]
                    current_city = city
        return routes_from_city

if __name__ == '__main__':
    atlanta = City('Atlanta')
    boston = City('Boston')
    chicago = City('Chicago')
    denver = City('Denver')
    el_paso = City('El Paso')

    atlanta.add_route(boston, 100)
    atlanta.add_route(denver, 160)
    boston.add_route(chicago, 120)
    boston.add_route(denver, 180)
    chicago.add_route(el_paso, 80)
    denver.add_route(chicago, 40)
    denver.add_route(el_paso, 140)

    routes = atlanta.dijkstra(atlanta, [boston, chicago, denver, el_paso])
    for my_city, my_price in routes.items():
        print(my_city.name, my_price[0])

# 打印结果:
# Atlanta 0
# Boston 100
# Chicago 200
# Denver 160
# El Paso 280
原文地址:https://www.cnblogs.com/glz666/p/13893316.html