这一题的算法就是按照坐标搜索,假设起始坐标是i, j ,按行搜索,c和r表示相对于i,j这个坐标的相对坐标,搜索到这一行最远为1的位置,然后继续搜索该坐标下面一行,算res = max(res, (c+1)*(r+1)),
代码如下:
class Solution(object):
def maximalRectangle(self, matrix):
"""
:type matrix: List[List[str]]
:rtype: int
"""
res = 0
if len(matrix) == 0:
return 0
m = len(matrix)
n = len(matrix[0])
res = 0
for i in range(m):
for j in range(n):
res = max(res, self.max_ij(matrix, i, j, m, n))
return res
def max_ij(self, matrix, i, j, m, n):
if matrix[i][j] == "0":
return 0
else:
c = 0
r = 0
res = 0
c_pre = n - 1
while j+c < n and i+r < m and matrix[i+r][j+c] == "1":
while j+c < n and i + r < m and c <= c_pre and matrix[i+r][j+c] == "1" :
c += 1
c -= 1
#print c
c = min(c, c_pre)
res = max(res, (c+1)*(r+1))
#print res
#print i + r
c_pre = c
r += 1
c = 0
return res