Dijsktra算法贪婪法python实现

Dijsktra算法贪婪法python实现

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pdb


# Dijsktra算法
def update(a,b, nodepair, G, n):
    # 函数实现代码开始
    # 请在其中写入你的代码
    if b == 0:
        return nodepair
    nodepair[b][0] = a
    nodepair[b][1] = G[a][b] + nodepair[a][1]
    # 函数实现代码结束
    return nodepair


def dijkstra(G, n):
    INF = 100000
    visit = [-1] * n  # 遍历情况记录数组

    nodepair = [[-1, INF] for i in range(n)]  # 节点伴随二元数组 第一个表示前一个索引preIndex,第二个表示距离

    # 先取第一个节点
    visit[0] = 1
    nodepair[0][1] = 0
    print(0, nodepair[0])  # 打印第一个节点
    # 更新节点伴随二元数组
    nodepair = update(0,0, nodepair, G, n)
    # 函数实现代码开始
    # 请在其中写入你的代码
    for key in range(1,n):
        tmp = INF
        for key1 in range(n):
            for key2 in range(n):
                if visit[key1]==1 and visit[key2]==-1:
                    if G[key1][key2] != 0:
                        if G[key1][key2]+nodepair[key1][1] < tmp:
                            a = key1
                            b = key2
                            tmp = G[key1][key2]
        visit[b] = 1
        nodepair = update(a,b, nodepair, G, n)
        print(b, nodepair[b])
    # 函数实现代码结束
    return nodepair


if __name__ == '__main__':
    Glist = input().split('-')
    G = []
    for item in Glist:
        row = item.split(',')
        g = [int(i) for i in row]
        G.append(g)
    n = len(G)
    dijkstra(G, n)

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,首先我们需要安装一些必要的库,包括`networkx`, `matplotlib`和`heapq`。你可以通过以下命令来安装它们: ```python pip install networkx matplotlib heapq ``` 接下来,我们可以开始编代码。以下是一个简单的实现: ```python import networkx as nx import matplotlib.pyplot as plt import heapq def dijkstra(G, start): distances = {node: float('inf') for node in G.nodes()} distances[start] = 0 pq = [(0, start)] while len(pq) > 0: (dist, current_node) = heapq.heappop(pq) if dist > distances[current_node]: continue for neighbor in G.neighbors(current_node): distance = G[current_node][neighbor]['weight'] total_distance = distances[current_node] + distance if total_distance < distances[neighbor]: distances[neighbor] = total_distance heapq.heappush(pq, (total_distance, neighbor)) return distances G = nx.Graph() G.add_edge('A', 'B', weight=7) G.add_edge('A', 'D', weight=5) G.add_edge('B', 'C', weight=8) G.add_edge('B', 'D', weight=9) G.add_edge('B', 'E', weight=7) G.add_edge('C', 'E', weight=5) G.add_edge('D', 'E', weight=15) G.add_edge('D', 'F', weight=6) G.add_edge('E', 'F', weight=8) G.add_edge('E', 'G', weight=9) G.add_edge('F', 'G', weight=11) pos = nx.spring_layout(G) nx.draw_networkx_nodes(G, pos) nx.draw_networkx_edges(G, pos) nx.draw_networkx_labels(G, pos) labels = nx.get_edge_attributes(G, 'weight') nx.draw_networkx_edge_labels(G, pos, edge_labels=labels) distances = dijkstra(G, 'A') print(distances) ``` 这个代码段创建了一个简单的图,并在其中运行Dijkstra算法以计算从节点A到其他节点的最短距离。我们使用了`networkx`库来创建和可视化图形,并使用`heapq`库来实现优先队列。 运行代码后,我们会看到输出结果为: ``` {'A': 0, 'B': 7, 'C': 15, 'D': 5, 'E': 12, 'F': 11, 'G': 20} ``` 这个结果表明从节点A到其他节点的最短距离,例如,从节点A到节点B的距离为7,从节点A到节点C的距离为15等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

migrant-worker

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值