繁体   English   中英

用邻接矩阵生成随机连通图 Python

[英]Generating random connected graph with adjacency matrix in Python

该代码生成随机图。 但是,我想在附带的 forms 中使用邻接矩阵生成方形(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)]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM