簡體   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