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

时间:2015-10-31 12:19:23

标签: python matrix

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

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.任何人都有一个想法改进?

3 个答案:

答案 0 :(得分:4)

一个直接的方法是说,“如果单元格在拐角处,它有三个邻居,否则如果它在边缘,它有五个,否则它有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

答案 1 :(得分:1)

现在设计的功能不符合您的指定。它包含行数和列数。然后它遍历矩阵的所有元素并计算邻居的数量。然后它返回最后计算的值,所以矩阵的右下角元素确实有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

答案 2 :(得分:0)

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

然后你钳制结果并返回元素数减1:

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

enter image description here

图像显示所选元素及其周围的放大框。最小/最大操作将切断额外的正方形,留下2x3的盒子,导致2 * 3-1 = 5个邻居计数。