221. Maximal Square
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
Solution
(1) Java
(2) Python
class Solution:
def maximalSquare(self, matrix):
"""
:type matrix: List[List[str]]
:rtype: int
"""
if not matrix or not matrix[0]:
return 0
m = len(matrix)
n = len(matrix[0])
dp = [[0 for j in range(n)] for i in range(m)]
rst = 0
for i in range(m):
for j in range(n):
if matrix[i][j] == '1':
if i == 0 or j == 0:
dp[i][j] = 1
rst = max(rst, dp[i][j])
else:
dp[i][j] = min(min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1])+1
rst = max(rst, dp[i][j]*dp[i][j])
return rst
(3) Scala