221. Maximal Square
https://leetcode.com/problems/maximal-square/description/
Input:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Output: 4Thoughts
Code
class Solution:
def maximalSquare(self, matrix: List[List[str]]) -> int:
M, N = len(matrix), len(matrix[0]) if len(matrix) > 0 else 0
dp = [[0] * (N + 1) for i in range(M + 1)]
res = 0
for i in range(1, M + 1):
for j in range(1, N + 1):
if matrix[i - 1][j - 1] == '0':
continue
dp[i][j] = min(min(dp[i - 1][j], dp[i - 1][j - 1]), dp[i][j - 1]) + 1
res = max(res, dp[i][j])
return res ** 2
Analysis
Last updated