题目描述
给定一个二维数组M行N列,二维数组里的数字代表图片的像素,为了简化问题,仅包含像素1和5两种像素,每种像素代表一个物体,2个物体相邻的格子为边界,求像素1代表的物体的边界个数。
像素1代表的物体的边界指与像素5相邻的像素1的格子,边界相邻的属于同一个边界,相邻需要考虑8个方向(上,下,左,右,左上,左下,右上,右下)。
……
仅供参考的答案如下:
M, N = map(int, input('M行N列:').split())
matrix = [list(map(int, input(f'矩阵第{i+1}行:').split()[:N])) for i in range(M)] # 列表里包含M个列表,每个列表里包含N个元素
offsets = ((-1, 0), (1, 0), (0, -1), (0, 1), (-1, -1), (-1, 1), (1, -1), (1, 1)) # 对应上、下、左、右、左上、右上、左下、右下位置
five_list = []
def count_boundary(x, y):
for t in offsets:
new_x = x + t[0]
new_y = y + t[1]
if 0 <= new_x < M and 0 <= new_y < N:
if matrix[new_x][new_y] == 2:
matrix[new_x][new_y] = 3
count_boundary(new_x, new_y)
def get_result(m, n):
result = 0
for i, j in five_list:
if matrix[i][j] == 5:
for t in offsets:
new_i = i + t[0]
new_j = j + t[1]
if 0 <= new_i < m and 0 <= new_j < n and matrix[new_i][new_j] == 2:
result += 1
count_boundary(new_i, new_j)
return result
for a in range(M):
for b in range(N):
if matrix[a][b] == 5:
five_list.append([a, b])
for c in offsets:
new_a = a + c[0]
new_b = b + c[1]
if 0 <= new_a < M and 0 <= new_b < N:
if matrix[new_a][new_b] == 1:
matrix[new_a][new_b] = 2
print(get_result(M, N))
欢迎交流