非赋权图:
import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
nodes = ['v1', 'v2', 'v3', 'v4', 'v5', 'v6']
G.add_nodes_from(nodes)
edges = [
('v1', 'v2'), ('v1', 'v3'), ('v1', 'v4'),
('v2', 'v3'), ('v2', 'v6'),
('v3', 'v4'),
('v4', 'v5'),
('v5', 'v6')
]
G.add_edges_from(edges)
pos = nx.circular_layout(G)
center = (0, 0)
pos['v1'] = center
plt.figure(figsize=(8, 8))
nx.draw(G, pos, with_labels=True, node_color='skyblue', node_size=700, font_size=15, font_weight='bold')
plt.title("Undirected Graph as Described")
plt.axis('equal')
plt.show()
print("学号:2023310143005")
赋权图:
`import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
nodes = ['v1', 'v2', 'v3', 'v4', 'v5', 'v6']
G.add_nodes_from(nodes)
edges = [
('v1', 'v2', 7),
('v1', 'v3', 3),
('v1', 'v4', 12),
('v2', 'v3', 1),
('v2', 'v6', 1),
('v3', 'v4', 8),
('v4', 'v5', 9),
('v5', 'v6', 3)
]
G.add_weighted_edges_from(edges)
pos = nx.circular_layout(G)
center = (0, 0)
pos['v1'] = center
def draw_edges_with_weights(G, pos):
edge_labels = {(u, v): d['weight'] for u, v, d in G.edges(data=True)}
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
plt.figure(figsize=(10, 10))
nx.draw(G, pos, with_labels=True, node_color='lightblue', node_size=700, font_size=15, font_weight='bold')
draw_edges_with_weights(G, pos)
plt.title("Undirected Graph with Weights")
plt.axis('equal')
plt.show()
print("学号:3005")`
有向图:
`import networkx as nx
import matplotlib.pyplot as plt
G = nx.DiGraph()
nodes = ['v1', 'v2', 'v3', 'v4', 'v5', 'v6']
G.add_nodes_from(nodes)
edges = [
('v2', 'v1', 7),
('v1', 'v3', 3),
('v4', 'v1', 12),
('v2', 'v3', 1),
('v6', 'v2', 1),
('v3', 'v4', 8),
('v5', 'v4', 9),
('v5', 'v6', 3)
]
G.add_weighted_edges_from(edges)
pos = nx.circular_layout(G)
def draw_edges_with_weights(G, pos):
edge_labels = {(u, v): d['weight'] for u, v, d in G.edges(data=True)}
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, font_color='red')
plt.figure(figsize=(10, 10))
nx.draw(G, pos, with_labels=True, node_color='lightblue', node_size=700, font_size=15, font_weight='bold', arrows=True)
draw_edges_with_weights(G, pos)
plt.title("Directed Graph with Weights")
plt.axis('equal')
plt.show()
print("学号:3005")`