简体   繁体   中英

Generating random connected graph with adjacency matrix in Python

The code generates random graphs. However, I would like to generate square (2x2,3x3,4x4,... nodes) connected graphs in the attached forms with the adjacency matrix.

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

在此处输入图像描述

You could use nx.grid_2d_graph() to produce a similar graph and then use the provided structure to adjust the labels:

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)

Nodes:

[1, 5, 2, 6, 3, 7, 4, 8, 9, 10, 11, 12, 13, 14, 15, 16]

Edges:

[(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)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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