Python 中二维网格图中的邻接矩阵问题

Problem with adjacency matrix in 2d grid graph in Python

代码生成二维网格图。但是,它生成的邻接矩阵存在问题。例如,节点 1 没有连接到 3 但在矩阵中,它显示值 1。对于节点 2,它显示值 0 即使它连接到节点 [=13] =] 和其他节点类似。附上邻接矩阵和二维网格图

import numpy as np
import networkx as nx

G = nx.grid_2d_graph(3,3)
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)
nx.draw(G, with_labels=True)

A1 = nx.adjacency_matrix(G) 
A=A1.toarray()
print([A]) 

Figure

我认为问题出在重新贴标签上。您可以使用 convert_node_labels_to_integers(G) 重新标记图表,以便更好地重新标记。 试试这个:

import numpy as np
import networkx as nx

G = nx.grid_2d_graph(3,3)
nodes= {i:n for i, n in enumerate(G.nodes, start=1)}
edges = {i:e for i, e in enumerate(G.edges, start=1)}
A1 = nx.adjacency_matrix(G) 
A=A1.toarray()
G = nx.convert_node_labels_to_integers(G)
G = nx.relabel_nodes(G, {node:node+1 for node in G.nodes})
nx.draw(G, with_labels=True,pos=nx.spring_layout(G))
A1 = nx.adjacency_matrix(G) 
A=A1.toarray()
print([A]) 

重新标记来自 networkx.com 的文档: https://networkx.org/documentation/stable/reference/relabel.html