LeetCode 221
首先我们考虑怎么找square,对于【i,j】,如果【i-1,j-1】是个square,【i,j】的行和列的长度都长于【i-1,j-1】的square,那么我们就组成一个更大的square。基于这个想法,我们就不断的求解行长和列长以及square的长度,然后求出最大的area。
def maximalSquare(self, matrix: List[List[str]]) -> int:
try:
m = len(matrix)
n = len(matrix[0])
except:
return 0
#行
dpr = [[0]*n for i in range(m)]
#列
dpc = [[0]*n for i in range(m)]
#square 长度
dpf = [[0]*n for i in range(m)]
maxarea = 0
for i in range(m):
for j in range(n):
if i == 0 and matrix[i][j] == '1':
dpc[i][j] = 1
if j == 0 and matrix[i][j] == '1':
dpr[i][j] = 1
if i !=0 and matrix[i][j] == '1':
dpc[i][j] = dpc[i-1][j] + 1
if j !=0 and matrix[i][j] == '1':
dpr[i][j] = dpr[i][j-1] + 1
if matrix[i][j] == '1':
if i == 0 or j == 0:
dpf[i][j] = min(dpc[i][j], dpr[i][j])
else:
dpf[i][j] = min(dpf[i-1][j-1] + 1, dpc[i][j], dpr[i][j])
maxarea = max(maxarea, dpf[i][j] * dpf[i][j])
return maxarea