作业6.1

zhhhhha / 2024-11-09 / 原文

(a)

点击查看代码
import matplotlib.pyplot as plt
 
# 创建一个无向图
G = nx.Graph()
 
# 添加节点
G.add_nodes_from([1, 2, 3, 4, 5, 6])
 
# 添加边
edges = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 6), (3, 4), (4, 5), (5, 6)]
G.add_edges_from(edges)
 
# 使用默认布局算法绘制图
pos = nx.spring_layout(G)
 
# 绘制图,其中 with_labels=True 表示显示节点标签,font_weight='bold' 表示节点标签加粗显示
nx.draw(G, pos, with_labels=True, font_weight='bold')
 
# 显示图
plt.show()
print("3010")

(b)

点击查看代码

import networkx as nx
import matplotlib.pyplot as plt
 
# 创建一个无向图
G = nx.Graph()
 
# 添加节点
G.add_nodes_from([1, 2, 3, 4, 5, 6])
 
# 添加带有权重的边
edges_with_weights = [(1, 2, 7), (1, 3, 3), (1, 4, 12), (2, 3, 1), (2, 6, 1), (3, 4, 8), (4, 5, 9), (5, 6, 3)]
G.add_weighted_edges_from(edges_with_weights)
 
# 使用默认布局算法绘制图
pos = nx.spring_layout(G)
 
# 获取边的权重信息
edge_labels = nx.get_edge_attributes(G, 'weight')
 
# 绘制图,其中 with_labels=True 表示显示节点标签,font_weight='bold' 表示节点标签加粗显示
nx.draw(G, pos, with_labels=True, font_weight='bold')
 
# 绘制边的权重信息
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
 
# 显示图
plt.show()
print("3010")

(c)

点击查看代码
import networkx as nx
import matplotlib.pyplot as plt
 
# 创建一个有向图
G = nx.DiGraph()
 
# 添加节点
G.add_nodes_from([1, 2, 3, 4, 5, 6])
 
# 添加带有权重的边
edges_with_weights = [(2, 1, 7), (1, 3, 3), (4, 1, 12), (2, 3, 1), (6, 2, 1), (3, 4, 8), (5, 4, 9), (5, 6, 3)]
G.add_weighted_edges_from(edges_with_weights)
 
# 使用默认布局算法绘制图
pos = nx.spring_layout(G)
 
# 获取边的权重信息
edge_labels = nx.get_edge_attributes(G, 'weight')
 
# 绘制图,其中 with_labels=True 表示显示节点标签,font_weight='bold' 表示节点标签加粗显示
nx.draw(G, pos, with_labels=True, font_weight='bold')
 
# 绘制边的权重信息
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
 
# 显示图
plt.show()
print("3010")