算法题:求最大子矩阵的大小
最近在看左程云的《程序员代码面试指南》,感觉不错,题都分了类,很方便有目的的刷题,书里的代码都是java实现的,刚好最近在学习python,就用python去练习一下。
1. 问题描述
给定一个整型矩阵map,其中的值只有0和1两种,求其中全是1的所有矩形区域中,最大的矩阵区域为1的数量
举例
矩阵 1 0 1 1
其中最大的矩形区域有3个1,所以返回3
矩阵
1 0 1 1
1 1 1 1
1 1 1 0
其中,最大的矩形区域有6个1,所以返回6
2. 解决方法
如果矩阵大小为O(NM),可以通过单调栈结构做到时间复杂度O(MN)。单调栈结构前面有写过。
从第一行开始,向下拓展,找到每一列从当前行开始,最高为height,放入数组arr中,再通过单调栈结构求解height左右两边的最近最小height的位置i,j,则面积显而易见,area = (i - k -1) * arr[j]。
3. 代码实现
首先写一个栈结构,直接用列表[ ]代替也可以
class Stack(object):
def __init__(self):
self.list = []
def is_empty(self):
if self.list:
return False
else:
return True
def pop(self):
if self.is_empty():
print('栈为空!')
return None
else:
result = self.list.pop()
return result
def push(self, item):
self.list.append(item)
def peek(self):
#查看栈顶元素
if self.is_empty():
print('栈为空!')
return None
return self.list[len(self.list) - 1]
def size(self):
#判断大小
return len(self.list)
求解每一行各元素height的函数
def maxRecSize(map): # 本函数用于求最大子矩阵,本函数对每一行进行分析,调用maxRecFromBottom()来进行求解
if not map:
print('无参数!')
maxArea = 0
height = [] # height代表以此行为低,各列的高度
for i in range(len(map[0])):
height.append(0)
i = 0
while i < len(map):
j = 0
while j < len(map[0]):
if map[i][j] == 0:
height[j] = 0
else:
height[j] = height[j] + 1
j += 1
maxArea = max(maxRecFromBottom(height), maxArea)
i += 1
return maxArea
为每一行的height数组进行求解最大面积
def maxRecFromBottom(arr): #被maxRecSize(map)调用
maxArea = 0
stack = Stack() #里面存储位置信息
i = 0
while i < len(arr):
while not stack.is_empty() and arr[stack.peek()] >= arr[i]:
j = stack.pop()
if stack.is_empty():
k = -1
else:
k = stack.peek()
curArea = (i - k -1) * arr[j]
maxArea = max(maxArea, curArea)
# print('位置{0},最大值{1}'.format(j, maxArea))
stack.push(i)
i += 1
while not stack.is_empty():
j = stack.pop()
if stack.is_empty():
k = -1
else:
k = stack.peek()
curArea = (len(arr) - k -1) * arr[j]
maxArea = max(maxArea, curArea)
# print('位置{0},最大值{1}'.format(j, maxArea))
return maxArea
主函数
if __name__ == "__main__":
# 求最大子矩阵
map = [[1, 0, 1, 1], [1, 1, 1, 1], [1, 1, 1, 0], ]
print('最大子矩阵大小为:{0}'.format(maxRecSize(map)))
pass
运行结果
最大子矩阵大小为:6