Maximal Square LeetCode solution in Python

1
class Solution:
2
def maximalSquare(self, matrix: List[List[str]]) -> int:
3
m, n = len(matrix), len(matrix[0])
4
result = 0
5
dp = [
6
[0] * n for _ in range(m)
7
] # dp[x][y] is the length of the maximal square at (x, y)
8
for i in range(m):
9
for j in range(n):
10
if matrix[i][j] == "1": # ensure this condition first
11
# perform computation, mind border restrictions
12
dp[i][j] = (
13
min(
14
dp[i - 1][j] if i > 0 else 0,
15
dp[i][j - 1] if j > 0 else 0,
16
dp[i - 1][j - 1] if i > 0 and j > 0 else 0,
17
)
18
+ 1
19
)
20
if dp[i][j] > result:
21
result = dp[i][j]
22
return result * result

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0