Problem
Given an m x n binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.
Algorithm
Dynamic Programming (DP). Tracks the largest square ending at (i,j). The key recurrence relation is derived from:
dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1
Code
python3
class Solution:
def maximalSquare(self, matrix: List[List[str]]) -> int:
m, n = len(matrix), len(matrix[0])
dp = [[0] * (n + 1) for _ in range(m + 1)]
ans = 0
for i in range(1, m + 1):
for j in range(1, n + 1):
if matrix[i-1][j-1] == '1':
dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1
if ans < dp[i][j]:
ans = dp[i][j]
return ans * ans