def find_local_peak(matrix): rows = len(matrix) cols = len(matrix[0])

def is_local_peak(row, col):
    # 检查当前元素是否是局部高点
    current = matrix[row][col]
    if row > 0 and current < matrix[row-1][col]:  # 上方元素更大
        return False
    if row < rows-1 and current < matrix[row+1][col]:  # 下方元素更大
        return False
    if col > 0 and current < matrix[row][col-1]:  # 左侧元素更大
        return False
    if col < cols-1 and current < matrix[row][col+1]:  # 右侧元素更大
        return False
    return True

def local_peak_helper(start_row, end_row, start_col, end_col):
    if start_row == end_row and start_col == end_col:
        return matrix[start_row][start_col]
    
    mid_row = (start_row + end_row) // 2
    col = matrix[mid_row].index(max(matrix[mid_row][start_col:end_col+1]))  # 找到该行的最大值对应的列索引

    if is_local_peak(mid_row, col):
        return matrix[mid_row][col]
    elif matrix[mid_row][col] < matrix[mid_row-1][col]:
        return local_peak_helper(start_row, mid_row-1, start_col, end_col)
    else:
        return local_peak_helper(mid_row+1, end_row, start_col, end_col)

return local_peak_helper(0, rows-1, 0, cols-1)
def find_local_peakmatrix rows = lenmatrix cols = lenmatrix0 def is_local_peakrow col # 检查当前元素是否是局部高点 current = matrixrowcol if row 0 and current matrixrow-1col # 上方元素

原文地址: https://www.cveoy.top/t/topic/i7Gq 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录