该代码生成一个 2D 网格图。然而,它生成的邻接矩阵存在问题。例如,节点1
未连接到3
,但在矩阵中,它显示值1。对于节点2
,它甚至显示值0尽管它连接到节点 3
,其他节点也类似。邻接矩阵和二维网格图附在此处。
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])
最佳答案
我认为问题在于重新标记。您可以使用 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
关于python - Python中二维网格图中的邻接矩阵问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71866862/