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.
Example 1:
Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]] Output: 4
Example 2:
Input: matrix = [["0","1"],["1","0"]] Output: 1
Example 3:
Input: matrix = [["0"]] Output: 0
Constraints:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 300
matrix[i][j]
is '0'
or '1'
.This problem aims to find the largest square within a binary matrix (containing only '0's and '1's) that consists entirely of '1's. The solution presented uses dynamic programming for optimal efficiency.
The core idea is to build a DP table where dp[i][j]
represents the side length of the largest square whose bottom-right corner is at the cell matrix[i][j]
.
State Transition:
The value of dp[i][j]
is determined as follows:
If matrix[i][j]
is '0': dp[i][j]
= 0. No square can be formed with a '0' at its bottom-right corner.
If matrix[i][j]
is '1': dp[i][j]
= 1 + min( dp[i-1][j]
, dp[i][j-1]
, dp[i-1][j-1]
). This is because extending the square requires considering the squares to the left, top, and top-left. The minimum of these three values determines the maximum size of a square that can be extended.
Base Case:
The first row and column of the DP table are initialized with the corresponding values from the input matrix. If the cell is '1', the initial value is 1; otherwise, it's 0.
Answer:
The maximum value in the DP table represents the side length of the largest square. The area is simply the square of this maximum side length.
Time Complexity: O(m*n), where 'm' and 'n' are the dimensions of the input matrix. This is because we iterate through the matrix once to populate the DP table.
Space Complexity: O(mn) to store the DP table. Note that, while it is possible to optimize this to O(n) by using only one row in the DP table (or two if you want to avoid in-place modification), the solution below sticks to the easier-to-understand O(mn) space usage.
def maximalSquare(matrix):
"""
Finds the largest square containing only 1s in a binary matrix.
Args:
matrix: A list of lists representing the binary matrix.
Returns:
The area of the largest square.
"""
rows = len(matrix)
cols = len(matrix[0]) if rows > 0 else 0 # Handle empty matrix case
# Initialize DP table (add extra row and column for padding)
dp = [[0] * (cols + 1) for _ in range(rows + 1)]
max_side = 0
for i in range(1, rows + 1):
for j in range(1, cols + 1):
if matrix[i - 1][j - 1] == '1':
dp[i][j] = 1 + min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1])
max_side = max(max_side, dp[i][j])
return max_side * max_side
The code in other languages (Java, C++, Go, C#) follows a very similar structure, employing the same dynamic programming approach. The only difference lies in the language-specific syntax and data structures. The core logic remains identical.