You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

19 lines
747 B

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

def find_neighbors(matrix, row, col):
rows = len(matrix)
cols = len(matrix[0])
neighbors = []
# 遍历周围的8个点包括对角线方向
for i in range(-1, 2):
for j in range(-1, 2):
# 排除当前点以及超出矩阵边界的点
if i == 0 and j == 0:
continue
if row + i >= 0 and row + i < rows and col + j >= 0 and col + j < cols:
neighbors.append(matrix[row + i][col + j])
return neighbors
# 构造10*10的二维矩阵
matrix = [[0] * 10 for i in range(10)]
# 遍历矩阵中的每个点,输出其周围点
for i in range(len(matrix)):
for j in range(len(matrix[0])):
print(f"({i}, {j}): {find_neighbors(matrix, i, j)}")