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

Python实现二维矩阵环绕式8邻域单元格获取的问题

Python 实现矩阵环绕式8邻域获取

需求说明

需要获取二维矩阵中每个单元格的全部8个邻域单元格,针对矩阵边界的单元格,要实现首尾行、列互为邻域的环绕效果(即矩阵上下边缘相连、左右边缘相连),确保每个单元格都能得到8个邻域。现有代码仅筛选了矩阵范围内的邻域,导致边界单元格邻域数量为3或5,无法满足需求。

现有代码

def getNeighbours(matrix): #function to get and store nighbor cells in a new matrix called neighbourMatrix
    m , n  = len(matrix), len(matrix[0])#generate size of neighbourMatrix from size of rows and columns of original matrix
    neighbourMatrix = [['' for j in range(n)] for i in range(m)]

    def idx_gen(y, x , m, n):#generate indeces of neighbour matrix based around which cell we are viewing in the originla matrix
        v = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1),(1, -1), (1, 0), (1, 1)]
        for val in v:
            if (0 <= y + val[0] < m) and (0 <= x + val[1] < n): 
                yield y + val[0] , x + val[1]

    for i in range(m):
        for j in range(n):#looping through matrix
            for idx in idx_gen(i, j, m, n):
                neighbourMatrix[i][j] += matrix[idx[0]][idx[1]] #initialize and store neighbor values
    return neighbourMatrix#return nighbors in matrix


#call function to get neighbouring cells and store it in a matrix called "neighbourMatrix"
neighbourMatrix = getNeighbours(matrix)
print("Neighbor matrix is:: ", neighbourMatrix)

问题根源

现有代码的idx_gen函数通过条件判断过滤了超出矩阵范围的索引,没有处理环绕逻辑,导致边界单元格无法获取跨边缘的邻域,最终邻域数量不足8个。

修改后的代码

核心是用取模运算处理索引,让超出范围的索引自动绕到矩阵的另一端:

def getNeighbours(matrix):
    m, n = len(matrix), len(matrix[0])
    neighbourMatrix = [['' for _ in range(n)] for _ in range(m)]

    def idx_gen(y, x, m, n):
        # 8个邻域的偏移量
        offsets = [(-1, -1), (-1, 0), (-1, 1),
                   (0, -1),          (0, 1),
                   (1, -1),  (1, 0), (1, 1)]
        for dy, dx in offsets:
            # 取模实现环绕:行索引超出时绕到首尾,列同理
            ny = (y + dy) % m
            nx = (x + dx) % n
            yield ny, nx

    for i in range(m):
        for j in range(n):
            for ny, nx in idx_gen(i, j, m, n):
                neighbourMatrix[i][j] += matrix[ny][nx]
    return neighbourMatrix


# 测试用例(对应原始待分析字符串)
matrix = [
    ['-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-'],
    ['-', '-', '-', '+', '-', '-', '-', '+', '-', '-', '-', '+', '-', '-', '+', '-', '-', '-', '-', '-'],
    ['-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '+', '-', '-', '-', '-', '-', '-'],
    ['+', '+', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '+', '-', '-', '-', '-', '-', '-'],
    ['-', '+', '-', '+', '-', '-', '-', '-', '+', '-', '-', '-', '-', '-', '-', '+', '-', '-', '-', '-'],
    ['-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-'],
    ['-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '+', '-', '-', '-', '-', '-', '-', '-', '+'],
    ['-', '-', '-', '-', '-', '-', '+', '-', '-', '-', '-', '+', '-', '-', '-', '-', '-', '-', '-', '+'],
    ['+', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-'],
    ['-', '-', '+', '-', '-', '-', '-', '-', '-', '-', '-', '+', '-', '-', '-', '-', '-', '-', '+', '-']
]

neighbourMatrix = getNeighbours(matrix)
print("Neighbor matrix is:: ", neighbourMatrix)

效果验证

修改后,每个单元格的邻域字符串长度均为8,实现了环绕式的8邻域获取。比如原矩阵第一行第一列的单元格,会把最后一行最后一列、最后一行第一列等边缘单元格作为邻域,完全满足首尾环绕的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 18:30:54