python输出n×n的方格矩阵_求N×N二元矩阵中只含零的最大矩形

该博客介绍了一个Python算法,用于在N×N的矩阵中找到包含最多零的最大矩形。算法通过迭代矩阵的行,将每行的零视为“柱状图”的条形高度,然后使用堆栈来找出最大的矩形。解决方案具有O(N)的时间复杂度和O(ncols)的空间复杂度。
摘要由CSDN通过智能技术生成

[Algorithm] works by iterating through

rows from top to bottom, for each row

solving this problem, where the

"bars" in the "histogram" consist of

all unbroken upward trails of zeros

that start at the current row (a

column has height 0 if it has a 1 in

the current row).

输入矩阵mat可以是任意的iterable,例如文件或网络流。一次只需要一行可用。#!/usr/bin/env python

from collections import namedtuple

from operator import mul

Info = namedtuple('Info', 'start height')

def max_size(mat, value=0):

"""Find height, width of the largest rectangle containing all `value`'s."""

it = iter(mat)

hist = [(el==value) for el in next(it, [])]

max_size = max_rectangle_size(hist)

for row in it:

hist = [(1+h) if el == value else 0 for h, el in zip(hist, row)]

max_size = max(max_size, max_rectangle_size(hist), key=area)

return max_size

def max_rectangle_size(histogram):

"""Find height, width of the largest rectangle that fits entirely under

the histogram.

"""

stack = []

top = lambda: stack[-1]

max_size = (0, 0) # height, width of the largest rectangle

pos = 0 # current position in the histogram

for pos, height in enumerate(histogram):

start = pos # position where rectangle starts

while True:

if not stack or height > top().height:

stack.append(Info(start, height)) # push

elif stack and height < top().height:

max_size = max(max_size, (top().height, (pos - top().start)),

key=area)

start, _ = stack.pop()

continue

break # height == top().height goes here

pos += 1

for start, height in stack:

max_size = max(max_size, (height, (pos - start)), key=area)

return max_size

def area(size):

return reduce(mul, size)

解是O(N),其中N是矩阵中的元素数。它需要O(ncols)额外的内存,其中ncols是矩阵中的列数。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值