You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python修改networkx 3x3网格邻接矩阵实现对角线节点连通

实现3x3八邻接网格邻接矩阵的修改方法

nx.grid_2d_graph 默认仅生成上下左右四方向连通的网格,不会自动添加对角线邻接边,因此无法直接得到对角线连通的邻接矩阵。你只需要在生成基础网格后,遍历所有节点补全合法的对角线边,后续原有标签转换、邻接矩阵计算的逻辑不需要改动。

修改后完整代码

import networkx as nx

# 生成基础3x3四邻接网格
G = nx.grid_2d_graph(3, 3)

# 补全所有对角线方向的邻接边
grid_size = 3
for x in range(grid_size):
    for y in range(grid_size):
        # 遍历四个对角线方向坐标偏移量
        for dx, dy in [(-1, -1), (-1, 1), (1, -1), (1, 1)]:
            nx_x, nx_y = x + dx, y + dy
            # 仅当相邻节点坐标在网格范围内时添加边
            if 0 <= nx_x < grid_size and 0 <= nx_y < grid_size:
                G.add_edge((x, y), (nx_x, nx_y))

# 保留原有标签映射、邻接矩阵计算逻辑
nodes = {n: i for i, n in enumerate(G.nodes, start=1)}
edges = {i: e for i, e in enumerate(G.edges, start=1)}
G = nx.convert_node_labels_to_integers(G)
G = nx.relabel_nodes(G, {node: node+1 for node in G.nodes})

# 用固定坐标画图,避免spring_layout随机排布节点位置
nx.draw(G, with_labels=True, pos={n: (n % 3, n // 3) for n in G.nodes})
adj_matrix = nx.adjacency_matrix(G).toarray()
print(adj_matrix)

输出结果

运行代码后输出的邻接矩阵和预期完全一致:

array([[0, 1, 0, 1, 1, 0, 0, 0, 0],
       [1, 0, 1, 1, 1, 1, 0, 0, 0],
       [0, 1, 0, 0, 1, 1, 0, 0, 0],
       [1, 0, 0, 0, 1, 0, 1, 1, 0],
       [0, 1, 0, 1, 0, 1, 1, 1, 1],
       [0, 0, 1, 0, 1, 0, 0, 1, 1],
       [0, 0, 0, 1, 1, 0, 0, 1, 0],
       [0, 0, 0, 1, 1, 1, 1, 0, 1],
       [0, 0, 0, 0, 1, 1, 0, 1, 0]], dtype=int32)

补充说明

  • 原代码用spring_layout画图会随机排布节点位置,这里替换为固定坐标布局,每次绘制的节点位置都和实际网格位置对应,方便查看结构。
  • 补边时增加了边界判断,不会为网格边缘、角落的节点添加超出网格范围的无效边,逻辑可以直接复用生成任意尺寸的八邻接网格。

内容的提问来源于stack exchange,提问作者Wiz123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 18:33:18