问题问我给定任何方阵,我需要使用递归函数找到最里面的方阵。
这是我的python代码:
def findInnerMatrix(matrix):
for i in range(0, len(matrix)):
for j in range(0, len(matrix)):
if len(matrix) % 2 != 0: #if matrix is odd
while len(matrix) > 1 and len(matrix[i]) > 1: #del elements until 1 element left
del matrix[i][j]
if len(matrix) % 2 == 0: #if length of matrix is even
while len(matrix) > 2 and len(matrix[i]) > 2: #del el until 2 rows of 2 el left
del matrix[i][j]
return matrix
还有...我还没有真正弄清楚逻辑,所以我也不知道如何递归地写它。
鉴于此输入: [[9, 13, 5, 2], [1, 11, 7, 6], [3, 7, 4, 1], [6, 0, 7, 10]] 它给了我一个输出: [[5, 2], [7, 6], [4, 1], [7, 10]] 所需的输出是: [[11, 7], [7, 4]] #中间两个矩阵中的中间两个元素
def get_innermost_square(matrix):
# Base case: when the matrix is 1x1 or empty
if len(matrix) <= 1:
return matrix
# Remove the first and last row
matrix = matrix[1:-1]
# Remove the first and last column
matrix = [row[1:-1] for row in matrix]
# Recursive call
return get_innermost_square(matrix)
# Example usage:
matrix = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]]
print(get_innermost_square(matrix))