在 Python 中生成具有邻接矩阵的随机连通图
Generating random connected graph with adjacency matrix in Python
代码生成随机图。但是,我想生成带有邻接矩阵的附加形式的正方形(2x2,3x3,4x4,...节点)连接图。
import networkx as nx
n = 5
p = 0.7
G = nx.generators.random_graphs.gnp_random_graph(n, p)
nx.draw(G, with_labels=True)
A1 = nx.adjacency_matrix(G)
A=A1.toarray()
print([A]) #for obtaining a random adjacency matrix
您可以使用 nx.grid_2d_graph()
生成类似的图形,然后使用提供的结构调整标签:
import networkx as nx
G = nx.grid_2d_graph(4, 4)
new_nodes = {e: n for n, e in enumerate(G.nodes, start=1)}
new_edges = [(new_nodes[e1], new_nodes[e2]) for e1, e2 in G.edges]
G = nx.Graph()
G.add_edges_from(new_edges)
节点:
[1, 5, 2, 6, 3, 7, 4, 8, 9, 10, 11, 12, 13, 14, 15, 16]
边缘:
[(1, 5), (1, 2), (5, 9), (5, 6), (2, 6), (2, 3), (6, 10), (6, 7), (3, 7),
(3, 4), (7, 11), (7, 8), (4, 8), (8, 12), (9, 13), (9, 10), (10, 14), (10, 11),
(11, 15), (11, 12), (12, 16), (13, 14), (14, 15), (15, 16)]
代码生成随机图。但是,我想生成带有邻接矩阵的附加形式的正方形(2x2,3x3,4x4,...节点)连接图。
import networkx as nx
n = 5
p = 0.7
G = nx.generators.random_graphs.gnp_random_graph(n, p)
nx.draw(G, with_labels=True)
A1 = nx.adjacency_matrix(G)
A=A1.toarray()
print([A]) #for obtaining a random adjacency matrix
您可以使用 nx.grid_2d_graph()
生成类似的图形,然后使用提供的结构调整标签:
import networkx as nx
G = nx.grid_2d_graph(4, 4)
new_nodes = {e: n for n, e in enumerate(G.nodes, start=1)}
new_edges = [(new_nodes[e1], new_nodes[e2]) for e1, e2 in G.edges]
G = nx.Graph()
G.add_edges_from(new_edges)
节点:
[1, 5, 2, 6, 3, 7, 4, 8, 9, 10, 11, 12, 13, 14, 15, 16]
边缘:
[(1, 5), (1, 2), (5, 9), (5, 6), (2, 6), (2, 3), (6, 10), (6, 7), (3, 7),
(3, 4), (7, 11), (7, 8), (4, 8), (8, 12), (9, 13), (9, 10), (10, 14), (10, 11),
(11, 15), (11, 12), (12, 16), (13, 14), (14, 15), (15, 16)]