📅  最后修改于: 2023-12-03 15:23:37.211000             🧑  作者: Mango
在一个二维矩阵中,我们定义山脉为某个元素在四个方向上比它大,即上下左右的元素都比它小。给定一个矩阵,编写一个算法来计算矩阵中山脉的数量。
def count_mountains(matrix):
count = 0
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] > 0:
if check_mountain(matrix, i, j):
count += 1
return count
def check_mountain(matrix, row, col):
if row < 0 or row >= len(matrix) or col < 0 or col >= len(matrix[0]):
return False
if matrix[row][col] < 0:
return False
# 标记为已访问
matrix[row][col] = -matrix[row][col]
if (row > 0 and matrix[row-1][col] > matrix[row][col]) or\
(row < len(matrix)-1 and matrix[row+1][col] > matrix[row][col]) or\
(col > 0 and matrix[row][col-1] > matrix[row][col]) or\
(col < len(matrix[0])-1 and matrix[row][col+1] > matrix[row][col]):
return False
if (row > 0 and not check_mountain(matrix, row-1, col)) or\
(row < len(matrix)-1 and not check_mountain(matrix, row+1, col)) or\
(col > 0 and not check_mountain(matrix, row, col-1)) or\
(col < len(matrix[0])-1 and not check_mountain(matrix, row, col+1)):
return False
return True