Question
Given a 2D binary matrix filled with 0’s and 1’s, find the largest square containing all 1’s and return its area.
For example, given the following matrix:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Return 4.
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
Hide Tags Dynamic Programming
Hide Similar Problems
Solution
Get idea from here
class Solution(object):
def maximalSquare(self, matrix):
"""
:type matrix: List[List[str]]
:rtype: int
"""
if matrix==None or len(matrix)==0:
return 0
m, n = len(matrix), len(matrix[0])
dp = [[0]*n for dummy in range(m)]
res = 0
for ind in range(m):
dp[ind][0] = 1 if matrix[ind][0]=='1' else 0
if dp[ind][0]>res:
res = dp[ind][0]
for ind in range(n):
dp[0][ind] = 1 if matrix[0][ind]=='1' else 0
if dp[0][ind]>res:
res = dp[0][ind]
for mind in range(1,m):
for nind in range(1,n):
if matrix[mind][nind]=='1':
dp[mind][nind] = min([ dp[mind-1][nind], dp[mind][nind-1], dp[mind-1][nind-1] ]) + 1
if dp[mind][nind]>res:
res = dp[mind][nind]
else:
dp[mind][nind] = 0
return res**2