繁体   English   中英

计算矩阵中邻居数量的最佳方法?

[英]Best way to compute amount of neighbours in matrix?

我需要编写一个函数def amountofNeighbours(row, column) ,该函数将到矩阵中某个元素的邻居数量打印出来。 例如,给定矩阵[[2, 3, 4], [5, 6, 7], [8, 9, 10]] ,元素2在位置[0] [0]上有三个邻居,而元素6在位置[1] [1]上有八个邻居。 我不确定处理这样的问题的最佳方法是什么。 我经历了所有的可能性,这给了我以下几点:

def amountofNeighbours(row, column):
    neighbours = 0
    for i in range(row):
        for j in range(column):
            if i == 0 and j == 0 or i == 0 and j == column - 1:
                neighbours = 3
            elif i == row - 1 and j == 0 or i == row-1 and j == column - 1:
                neighbours = 3

            elif i > 0 and j == 0 or i == 0 and j > 0:
                neighbours = 5

            elif i == row - 1 and j > 0:
                neighbours = 5

            elif j == column - 1 and i > 0:
                neighbours = 5

            else:
                neighbours = 8

    return neighbours

当我用amountofNeighbours(1, 1)调用它时,它给了我正确的答案,即3,但是如果我用amountofNeighbours(2,2)调用了它,答案应该是8,而它给了我3。任何人都有改进的想法?

直接做到这一点的方法是说:“如果该单元在拐角处,则有三个邻居,否则,如果在边缘,则有五个,否则有8个。”

def numberOfNeighbors(rows, columns, row, column):
    topBottom = row in (0, rows-1)
    leftRight = column in (0, columns-1)
    if topBottom and leftRight:
       return 3
    if topBottom or leftRight:
       return 5
    return 8

现在设计的功能无法执行您指定的功能。 它接受行数和列数。 然后,它遍历矩阵的所有元素并计算邻居数。 然后,它返回最后一次计算出 ,因此矩阵的右下角元素实际上有3个邻居。

您应该摆脱循环,让它做您想要的事情。 澄清:

def amountofNeighbours(row, column, n_rows, n_cols):
    neighbours = 0
    if row == 0 and column == 0 or row == 0 and column == n_cols - 1:
        neighbours = 3
    elif row == n_rows - 1 and column == 0 or row == n_rows-1 and column == n_cols - 1:
        neighbours = 3

    elif row > 0 and column == 0 or row == 0 and column > 0:
        neighbours = 5

    elif row == n_rows - 1 and column > 0:
        neighbours = 5

    elif column == n_cols - 1 and row > 0:
        neighbours = 5

    else:
        neighbours = 8

    return neighbours

避免许多IF的一种解决方案是从元素开始,并在元素周围计算一个“放大”框(3x3正方形),该框可能部分位于矩阵外部。

然后将结果钳位,并返回减去一的元素数:

def neighbors(row, col, rows, cols):
    ra, rb = row-1, row+2
    ca, cb = col-1, col+2
    dx = min(cb, cols) - max(0, ca)
    dy = min(rb, rows) - max(0, ra)
    return dx*dy - 1

在此处输入图片说明

该图显示了选定的元素及其周围的放大框。 最小/最大运算将切除多余的正方形,剩下一个2x3的框,导致2 * 3-1 = 5个邻居计数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM