Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.
Example:
Input:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Output: 4
Accepted
191,572
Submissions
539,890
---------------------------------------------------------------------------------------------------------
非常好的题目!!!刚开始的想法是用dp[i][j]表示以(i,j)作为左上角的全1正方形对角线长度是多少。所以dp[i][j]可以一层一层的求,当无法继续扩大的时候,dp[i][j]就算好了,被dp[i][j]覆盖的点可以以此为基础继续扩大。时间复杂度可以做到O(m*n),但是写起来比较烦躁。。。
别人好的做法是以(i,j)作为右下角的全1正方形对角线长度是多少。这样对于当前点为1的情况,dp[i][j]=min(dp[i-1][j-1],dp[i][j-1],dp[i-1][j])+1,所以,还是得会脑筋急转弯啊。。。
class Solution:
def maximalSquare(self, matrix: List[List[str]]) -> int:
rows,cols = len(matrix),0 if len(matrix) == 0 else len(matrix[0])
if (rows == 0 or cols == 0):
return 0
dp = [[0 for j in range(cols+1)] for i in range(rows+1)]
res = 0
for i in range(1, 1+rows):
for j in range(1, 1+cols):
if (matrix[i-1][j-1] == '1'):
dp[i][j] = min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]) + 1
res = max(dp[i][j], res)
return res*res