通过交换Python中允许的列来找到1的最大矩形
假设我们有一个二进制矩阵,我们必须在该给定矩阵中找到所有1的最大矩形。可以通过交换或交换该矩阵的任何一对列来构建矩形。
所以,如果输入像
那么在这种情况下,输出将为6。可以通过将列1与3交换来生成矩形。交换后的矩阵为-
为了解决这个问题,我们将遵循以下步骤-
行:=垫子的尺寸
col:=垫子的尺寸[0]
temp:=阶数(行+1)x(col+1)的矩阵,并用0填充
因为我的范围是0到col,
如果mat[j,i]等于0,则
除此以外,
temp[j,i]:=0
temp[j,i]:=temp[j-1,i]+1
temp[0,i]:=mat[0,i]
对于范围1至行中的j,执行
对于范围在0到行之间的i,执行
如果cnt[j]>0,则
j:=j-1
temp[i,col_no]:=j
col_no:=col_no+1
对于0到cnt[j]范围内的k,执行
cnt[temp[i,j]]:=cnt[temp[i,j]]+1
cnt:=一个大小为(行+1)的数组,并用0填充
对于范围0到col的j,增加1,执行
col_no:=0
j:=行
当j>=0时
area_maximum:=0
对于范围在0到行之间的i,执行
area_current:=(j+1)*temp[i,j]
如果area_current>area_maximum,则
area_maximum:=area_current
对于范围0到col的j,执行
返回area_maximum
例
让我们看下面的实现以更好地理解-
def maxArea(mat):
row = len(mat)
col = len(mat[0])
temp = [[0 for i in range(col + 1)] for i in range(row + 1)]
for i in range(0, col):
temp[0][i] = mat[0][i]
for j in range(1, row):
if ((mat[j][i] == 0)):
temp[j][i] = 0
else:
temp[j][i] = temp[j - 1][i] + 1
for i in range(0, row):
cnt = [0 for i in range(row + 1)]
for j in range(0, col, 1):
cnt[temp[i][j]] += 1
col_no = 0
j = row
while(j >= 0):
if (cnt[j] > 0):
for k in range(0, cnt[j]):
temp[i][col_no] = j
col_no += 1
j -= 1
area_maximum = 0
for i in range(0, row):
for j in range(0, col):
area_current = (j + 1) * temp[i][j]
if (area_current > area_maximum):
area_maximum = area_current
return area_maximum
mat = [
[0, 0, 1, 1, 0],
[0, 0, 1, 1, 1],
[1, 0, 1, 1, 0]]
print("Area : ",maxArea(mat))输入项
[ [1, 0, 0, 1, 0], [1, 0, 0, 1, 1], [1, 1, 0, 1, 0]]
输出结果
Area : 2