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