这里,如果两个单元共享边界,则它们被视为相邻。 例如:
A = 5 6 4
2 1 3
7 9 8
这里索引 0,0 的相邻元素位于索引 [0,1] 和 [1,0] 处,索引 1,1 的相邻元素位于索引 [0,1],[1,0],[2, 1] 和 [1,2]。
假设你有
m
xn
矩阵,并且你想找到单元格的相邻索引 (i
, j
):
def get_adjacent_indices(i, j, m, n):
adjacent_indices = []
if i > 0:
adjacent_indices.append((i-1,j))
if i+1 < m:
adjacent_indices.append((i+1,j))
if j > 0:
adjacent_indices.append((i,j-1))
if j+1 < n:
adjacent_indices.append((i,j+1))
return adjacent_indices
为了检查对角线,关于 Casper Dijkstrao 提出的问题,我通常会编写如下代码:
def adj_finder(matrix, position):
adj = []
for dx in range(-1, 2):
for dy in range(-1, 2):
rangeX = range(0, matrix.shape[0]) # X bounds
rangeY = range(0, matrix.shape[1]) # Y bounds
(newX, newY) = (position[0]+dx, position[1]+dy) # adjacent cell
if (newX in rangeX) and (newY in rangeY) and (dx, dy) != (0, 0):
adj.append((newX, newY))
return adj
该函数获取
参数来提取其行和列的大小(我使用matrix
,因此numpy
返回matrix.shape
元组)。(row_size, column_size)
它还获取当前单元格作为
参数(就像pointer
)。(X,Y)
然后它生成相邻的单元格,如果它们是合法的(1.它们没有超出边界,并且2.与参考位置不同),它将它们添加到相邻列表中,
。adj
我想强调的是,使用上述算法,您也可以轻松获得更远距离的邻居。只需修改 for 循环中的范围,如下所示:
for v in range(0-distance, 1+distance):
for h in range(0-distance, 1+distance):
...
其中
是您想要进入的相邻的最大距离。distance
这将是另一种方式 - 概率。涉及一些数学技巧或被认为更简洁(如果您更喜欢数学):
def neighbours(grid, r, c):
vals = sum((row[c -(c>0): c+2]
for row in grid[r -(r>0):r+2]), [])
vals.remove(grid[r][c]) # rm itself.
return vals
grid = [[1, 5, 4, 9],
[2, 8, 3, 8],
[6, 3, 6, 3],
[7, 4, 7, 1]]
输出:(所有项目均按顺序)
print(f' {neighbours(grid, 2, 2)} ') # [8, 3, 8, 3, 3, 4, 7, 1]
print(f' {neighbours(grid, 0, 0)} ') # [5, 2, 8]
print(f' {neighbours(grid, 1, 1)} ') # [[1, 5, 4, 2, 3, 6, 3, 6]
我的回答可能不如其他回复那么干净。
但我喜欢这种方法的模块化。
from typing_extensions import Literal
def get_adjacent_indices(input_list:list, index_y:int, index_x:int, return_as:Literal['index', 'value']='index') -> list:
"""Get the adjacent indices of the given index in the given list
Parameters
----------
input_list : list
The list to get the adjacent indices from
index_y : int
The y index of the index to get the adjacent indices from
index_x : int
The x index of the index to get the adjacent indices from
return_as : Literal['index', 'value'], optional
The type to return the adjacent indices as, by default 'index'
Returns
-------
list
The adjacent indices of the given index in the given list (as the given type)
"""
# Get the y and x size of the list
size_y, size_x = len(input_list), len(input_list[0])
adjacent_indice_lst = []
# Iterate over the y range
for y in range(index_y-1, index_y+2):
# Iterate over the x range
for x in range(index_x-1, index_x+2):
# Check if the y and x are in range
# Also check if the y and x are not the same as the index
if y < 0 or y >= size_y or x < 0 or x >= size_x or (y == index_y and x == index_x):
continue
if return_as == 'index':
# Add the index to the adjacent_indiece_lst
adjacent_indice_lst.append((y, x))
elif return_as == 'value':
# Add the value to the adjacent_indice_lst
adjacent_indice_lst.append(input_list[y][x])
return adjacent_indice_lst
没有评论from typing_extensions import Literal
def get_adjacent_indices(input_list:list, index_y:int, index_x:int, return_as:Literal['index', 'value']='index') -> list:
size_y, size_x = len(input_list), len(input_list[0])
adjacent_indice_lst = []
for y in range(index_y-1, index_y+2):
for x in range(index_x-1, index_x+2):
if y < 0 or y >= size_y or x < 0 or x >= size_x or (y == index_y and x == index_x):
continue
if return_as == 'index':
adjacent_indice_lst.append((y, x))
elif return_as == 'value':
adjacent_indice_lst.append(input_list[y][x])
return adjacent_indice_lst
输出test_list = ['1234', '6789', 'abcd', 'efgh']
print(get_adjacent_indices(test_list, 1, 1)) # [(0, 0), (0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1), (2, 2)]
print(get_adjacent_indices(test_list, 2, 1, 'value')) # ['6', '7', '8', 'a', 'c', 'e', 'f', 'g']
print(get_adjacent_indices(test_list, 0, 0, 'value')) # ['2', '6', '7']