python -- Dijkstra算法

来源:互联网 发布:怎么进入淘宝客买东西 编辑:程序博客网 时间:2024/05/16 14:14
#! /usr/bin/env python3# -*- coding: utf-8 -*-graph = {}graph["起点"] = {}graph["起点"]["武汉"] = 5graph["起点"]["岳阳"] = 2graph["武汉"] = {}graph["武汉"]["长沙"] = 4graph["武汉"]["广州"] = 2graph["岳阳"] = {}graph["岳阳"]["武汉"] = 8graph["岳阳"]["广州"] = 7graph["长沙"] = {}graph["长沙"]["深圳"] = 3graph["长沙"]["广州"] = 6graph["广州"] = {}graph["广州"]["深圳"] = 1graph["深圳"] = {}infinity = float("inf")costs = {}costs["起点"] = 0costs["武汉"] = infinitycosts["岳阳"] = infinitycosts["广州"] = infinitycosts["长沙"] = infinitycosts["深圳"] = infinityparents = {}parents["武汉"] = "起点"parents["岳阳"] = "起点"parents["深圳"] = Noneprocessed = []path = []def find_lowest_cost_node(tb_costs):lowest = infinitylowest_node = Nonefor node in tb_costs:cc = costs[node]if cc < lowest and node not in processed:lowest = cclowest_node = nodereturn lowest_nodedef dijkstra():node = find_lowest_cost_node(costs)while node is not None:path.append(node)cost = costs[node]neighbors = graph[node]for i in neighbors.keys():new_cost = cost + neighbors[i]if new_cost < costs[i]:costs[i] = new_costparents[i] = nodeelif node in path:path.remove(node)processed.append(node)node = find_lowest_cost_node(costs)if __name__ == "__main__":dijkstra()print(costs["深圳"])print(costs)print(path)

原创粉丝点击