在矩阵中查找邻居?

时间:2014-03-21 04:40:28

标签: python

这是一个7x7矩阵:

11  21  31  41  51  61  71
12  22  32  42  52  62  72
13  23  33  43  53  63  73
14  24  34  44  54  64  74
15  25  35  45  55  65  75
16  26  36  46  56  66  76
17  27  37  47  57  67  77

数字11, 21, 33 ...是位置的值。 如果给出半径,行数和列数,如何找到邻居?

例如,函数neighbors(radius = 1, rowNumber = 3, columnNumber = 3)应该返回一个矩阵:

22  32  42
23  33  43
24  34  44

function neighbors(radius = 2, rowNumber = 3, columnNumber = 3)应该返回一个矩阵:

11  21  31  41  51
12  22  32  42  52
13  23  33  43  53
14  24  34  44  54
15  25  35  45  55

当邻居超出边界时,其值应为0。 例如,function neighbors(radius = 2, rowNumber = 1, columnNumber = 1)应返回矩阵

0   0   0   0   0
0   0   0   0   0
0   0   11  21  31
0   0   12  22  32
0   0   13  23  33

我已经对这个问题进行了3天的讨论,但我仍然无法为它开发解决方案。

5 个答案:

答案 0 :(得分:3)

在其他语言中可能很难,但在Python中这很容易。这是一个可以执行您要求的功能:

def neighbors(radius, rowNumber, columnNumber):
     return [[a[i][j] if  i >= 0 and i < len(a) j >= 0 and j < len(a[0]) else 0
                for j in range(columnNumber-1-radius, columnNumber+radius)]
                    for i in range(rowNumber-1-radius, rowNumber+radius)]

这是一个2D列表:

 a = [[ 11,  21,  31,  41,  51,  61,  71],
      [ 12,  22,  32,  42,  52,  62,  72],
      [ 13,  23,  33,  43,  53,  63,  73],
      [ 14,  24,  34,  44,  54,  64,  74],
      [ 15,  25,  35,  45,  55,  65,  75],
      [ 16,  26,  36,  46,  56,  66,  76],
      [ 17,  27,  37,  47,  57,  67,  77]]

请参阅List comprehensions

答案 1 :(得分:2)

我原来的解决方案不正确,@ Gnijuohz是正确的。以下是@ Gnijuohz的解决方案,除了函数采用矩阵(list list s)作为第一个参数,列表理解已被嵌套for替换环路。

def neighbors(mat, row, col, radius=1):

    rows, cols = len(mat), len(mat[0])
    out = []

    for i in xrange(row - radius - 1, row + radius):
        row = []
        for j in xrange(col - radius - 1, col + radius):

            if 0 <= i < rows and 0 <= j < cols:
                row.append(mat[i][j])
            else:
                row.append(0)

        out.append(row)

    return out

答案 2 :(得分:2)

此代码以2d数组(矩阵)为参数,并返回所有邻居的元素列表。

输入:

 arr = [['a', 'b', 'c'],
        ['d', 'e', 'f'],
        ['g', 'h', 'k']]

输出:

[{'value': 'a', 'neighbors': ['b', 'd']}
 {'value': 'b', 'neighbors': ['c', 'e', 'a']}
 {'value': 'c', 'neighbors': ['f', 'b']}
 {'value': 'd', 'neighbors': ['a', 'e', 'g']}
 {'value': 'e', 'neighbors': ['b', 'f', 'h', 'd']}
 {'value': 'f', 'neighbors': ['c', 'k', 'e']}
 {'value': 'g', 'neighbors': ['d', 'h']}
 {'value': 'h', 'neighbors': ['e', 'k', 'g']}
 {'value': 'k', 'neighbors': ['f', 'h']}]

更多详细信息-> GitHub

def find_neighbours(arr):

    neighbors = []

    for i in range(len(arr)):
        for j, value in enumerate(arr[i]):

            if i == 0 or i == len(arr) - 1 or j == 0 or j == len(arr[i]) - 1:
                # corners
                new_neighbors = []
                if i != 0:
                    new_neighbors.append(arr[i - 1][j])  # top neighbor
                if j != len(arr[i]) - 1:
                    new_neighbors.append(arr[i][j + 1])  # right neighbor
                if i != len(arr) - 1:
                    new_neighbors.append(arr[i + 1][j])  # bottom neighbor
                if j != 0:
                    new_neighbors.append(arr[i][j - 1])  # left neighbor

            else:
                # add neighbors
                new_neighbors = [
                    arr[i - 1][j],  # top neighbor
                    arr[i][j + 1],  # right neighbor
                    arr[i + 1][j],  # bottom neighbor
                    arr[i][j - 1]   # left neighbor
                ]

            neighbors.append({
                "value": value,
                "neighbors": new_neighbors})

    return neighbors

答案 3 :(得分:1)

我喜欢在2d数组上进行操作时使用边界检查功能。这段代码并没有完全符合您的要求(从左上角开始),但它应该足以让您振作起来。

matrix = [
[11, 21, 31, 41, 51, 61, 71],
[12, 22, 32, 42, 52, 62, 72],
[13, 23, 33, 43, 53, 63, 73],
[14, 24, 34, 44, 54, 64, 74],
[15, 25, 35, 45, 55, 65, 75],
[16, 26, 36, 46, 56, 66, 76],
[17, 27, 37, 47, 57, 67, 77] ]

def in_bounds(matrix, row, col):
    if row < 0 or col < 0:
        return False
    if row > len(matrix)-1 or col > len(matrix)-1:
        return False
    return True

def neighbors(matrix, radius, rowNumber, colNumber):
    for row in range(radius):
        for col in range(radius):
            if in_bounds(matrix, rowNumber+row, colNumber+col):
                print str(matrix[rowNumber+row][colNumber+col]) + " ",
        print ""

neighbors(matrix, 2, 1, 1)

答案 4 :(得分:0)

有点晚了,但我写了一些东西来寻找给定搜索半径的邻居。

def nearest_neighout(array, row_idx, col_idx, radius):
    #input
    #array : 2D float64/int : data array to find the nearest neighours from
    #row_idx : int : row index for the center point for which nearest neighour needs to be searched
    #col_idx : int : index for the center point for which nearest neighour needs to be searched
    
    #output
    #returns a list
    #index of the nearest neighours
    #value at that cell
    
    #i iterates over row
    #j iterates over column
    
    above_i = row_idx + radius + 1 #defines the higher limt of row iterator
    if above_i > len(array) - 1: #takes into account the array length to avoid crossing index limits
        above_i = len(array)
    
    below_i = row_idx - radius #defines lower limit
    if below_i < 0: #takes into account the zero index
        below_i = 0
        
        
    above_j = col_idx + radius + 1 #defines the higher limit of column iterator
    if above_j > len(array) - 1: #takes the end index into account
        above_j = len(array)
    
    below_j = col_idx - radius #defines the lower limit of column iterator
    if below_j < 0: #takes zero index into account
        below_j = 0
        
    indices = list()
    for i in range(below_i, above_i):
        for j in range(below_j, above_j):
            indices.append(i, j, array[i,j])
    
    return indices