随笔 - 10  文章 - 0  评论 - 0  阅读 - 52

作业6.3 6.4

6.3

点击查看代码
import numpy as np
import networkx as nx
import pylab as plt
 
L=[(1,2,20),(1,5,15),(2,3,20),(2,4,60),(2,5,25),(3,4,30),(3,5,18),(4,5,35),(4,6,10),(5,6,15)]
G=nx.Graph()
G.add_weighted_edges_from(L)#添加赋权边
T=nx.minimum_spanning_tree(G)#返回可迭代对象
c=nx.to_numpy_array(T)#返回最小生成树的邻接矩阵
print("邻接矩阵c=\n",c)
w=c.sum()/2#求最小生成树的权重
print("最小生成树的权重W=",w)
pos=nx.circular_layout(G)
 
plt.subplot(121)#下面画连通图
nx.draw(G,pos,with_labels=True,font_size=13)
w1=nx.get_edge_attributes(G,'weight')
nx.draw_networkx_edge_labels(G,pos,edge_labels=w1)
 
plt.subplot(122)#下面画最小生成树
nx.draw(T,pos,with_labels=True,font_weight='bold')
w2=nx.get_edge_attributes(T,'weight')
nx.draw_networkx_edge_labels(T,pos,edge_labels=w2)
plt.show()
print("3010")

6.4

点击查看代码
import networkx as nx
import matplotlib.pyplot as plt
 
if __name__ == "__main__":
    graph = nx.DiGraph()  # 创建有向图
    graph.add_edge("v1", "v2", weight=0.8)
    graph.add_edge("v1", "v3", weight=2)
    graph.add_edge("v1", "v4", weight=3.8)
    graph.add_edge("v1", "v5", weight=6)
    graph.add_edge("v2", "v3", weight=0.9)
    graph.add_edge("v2", "v4", weight=2.1)
    graph.add_edge("v2", "v5", weight=3.9)
    graph.add_edge("v3", "v4", weight=1.1)
    graph.add_edge("v3", "v5", weight=2.3)
    graph.add_edge("v4", "v5", weight=1.4)
 
    res = nx.shortest_path(
        graph, "v1", "v5", weight="weight", method="dijkstra"
    )  # 使用dijkstra算法求解最短路径
    # 计算指定路径的权重和
    total_weight = 0
    for i in range(len(res) - 1):
        u = res[i]
        v = res[i + 1]
        total_weight += graph[u][v]["weight"]
    print("最短路径为", res)
    print("最短路径长度为", total_weight)
 
    # 画图
    plt.figure(figsize=(8, 6))
    pos = nx.spring_layout(graph)
    nx.draw(graph, pos, with_labels=True, node_size=500, node_color="skyblue", font_size=12, font_weight="bold") # 绘制有向图的节点
    nx.draw_networkx_edge_labels(graph, pos, edge_labels={(u, v): d["weight"] for u, v, d in graph.edges(data=True)}) # 绘制整个有向图的边界
    nx.draw_networkx_edges(graph, pos, edgelist=[(res[i], res[i + 1]) for i in range(len(res) - 1)], edge_color="red", width=2) # 绘制最短路径边界
    plt.title("Shortest Path")
    plt.show()
print("3010")

posted on   zzzhhhhha  阅读(3)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示