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

如何高效生成含对角线邻接的L×L网格邻接矩阵?

优化L×L网格含对角线邻接矩阵的生成效率

现有一个L×L网格,其中L为元素总数N的平方根(L=numpy.sqrt(N)),需要生成包含对角线相邻点的邻接矩阵。我已实现相关算法,但认为其效率有待提升,特此寻求更优解决方案。

原实现代码

import numpy as np

def get_2D_proximity(sqr_nblocks):
    ncol = sqr_nblocks
    nblocks = sqr_nblocks**2
    adj_mtx = np.zeros([nblocks, nblocks])

    for cell in range(ncol**2):
        ## 右侧相邻
        if (cell+1) % ncol == 0:
            pass
        else:
            adj_mtx[cell, cell+1] = 1
        ## 下方相邻
        if cell >= ncol*(ncol-1):
            pass
        else:
            adj_mtx[cell, cell+ncol] = 1

        ## 右下对角线相邻
        if ((cell+1) % ncol == 0) | (cell >= ncol*(ncol-1)):
            pass
        else:
            adj_mtx[cell, cell+1+ncol] = 1

        ## 左下对角线相邻
        if ((cell) % ncol == 0) | (cell >= ncol*(ncol-1)):
            pass
        else:
            adj_mtx[cell, cell-1+ncol] = 1 

        upper_triangle_idx = np.triu_indices(adj_mtx.shape[0], k=1)
        adj_mtx.T[upper_triangle_idx] = adj_mtx[upper_triangle_idx]
    return adj_mtx 

print(get_2D_proximity(3))

输出结果

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., 1., 0., 0., 1., 0., 1., 1., 0.],
       [1., 1., 1., 1., 0., 1., 1., 1., 1.],
       [0., 1., 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.]])

邻接矩阵可视化

邻接矩阵的可视化表示


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 00:00:17