The problem “Maximal Square” is described as follows:
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.
1 <= m, n <= 300
To solve this problem, we can use a dynamic programming approach. The main idea is to create a DP table where dp[i][j]
represents the side length of the largest square whose bottom-right corner is at cell (i, j)
.
Here’s a step-by-step strategy:
dp
of the same dimensions as the input matrix.matrix[i][j] == '1'
, initialize the first row and first column of dp
table with the same values as the matrix, because they can only form a square of side 1 (if they are ‘1’).(i, j)
, if matrix[i][j] == '1'
, then calculate dp[i][j]
as:
dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1
(i, j)
can only form a square if its top, left, and top-left neighbors also have the potential to contribute to a square.dp
table.class Solution {
public int maximalSquare(char[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return 0;
}
int m = matrix.length;
int n = matrix[0].length;
int[][] dp = new int[m][n];
int maxSide = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == '1') {
if (i == 0 || j == 0) {
dp[i][j] = 1;
} else {
dp[i][j] = Math.min(Math.min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1]) + 1;
}
maxSide = Math.max(maxSide, dp[i][j]);
}
}
}
return maxSide * maxSide;
}
}
This solution efficiently finds the largest square of ‘1’s in the given matrix using dynamic programming principles. If you have any further questions or need additional optimizations, feel free to ask!
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?