以下是一个示例代码,用于捕捉符合条件的相邻单元格:
def find_adjacent_cells(matrix, row, col, condition):
# 获取矩阵的行数和列数
rows = len(matrix)
cols = len(matrix[0])
# 定义相邻单元格的四个方向
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
# 存储符合条件的相邻单元格
adjacent_cells = []
# 遍历相邻单元格的四个方向
for direction in directions:
new_row = row + direction[0]
new_col = col + direction[1]
# 判断相邻单元格是否在矩阵范围内
if 0 <= new_row < rows and 0 <= new_col < cols:
# 判断相邻单元格是否符合条件
if condition(matrix[new_row][new_col]):
adjacent_cells.append((new_row, new_col))
return adjacent_cells
使用示例:
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# 定义条件函数,判断单元格的值是否为偶数
def is_even(value):
return value % 2 == 0
# 捕捉行索引为1,列索引为1的单元格的相邻单元格
adjacent_cells = find_adjacent_cells(matrix, 1, 1, is_even)
print(adjacent_cells) # 输出 [(0, 1), (2, 1), (1, 0), (1, 2)]
在上述示例中,我们定义了一个find_adjacent_cells
函数,它接收一个矩阵、行索引、列索引和条件函数作为参数。该函数会遍历相邻单元格的四个方向,并判断相邻单元格是否符合条件。如果符合条件,则将其添加到adjacent_cells
列表中,并在最后返回该列表。