Related: Leetcode 85 - Maximal Rectangle
http://www.geeksforgeeks.org/maximum-size-sub-matrix-with-all-1s-in-a-binary-matrix/
Given a matrix consisting only 0s and 1s, find the maximum size square sub-matrix with all 1s.
Time Complexity: O(m*n)
Auxiliary Space: O(m*n)
The idea of the algorithm is to construct an auxiliary size matrix S[][] in which each entry S[i][j] represents size of the square sub-matrix with all 1s including M[i][j] where M[i][j] is the rightmost and bottommost entry in sub-matrix.
https://leetcode.com/articles/maximal-square/
https://discuss.leetcode.com/topic/20801/extremely-simple-java-solution
http://www.programcreek.com/2014/06/leetcode-maximal-square-java/
Maximum size square sub-matrix with all 1s | PROGRAMMING INTERVIEWS
We will use a auxiliary matrix S[][] of same size for memoization. S[i][j] represents size of the square sub-matrix with all 1s including M[i][j]. 'i' and 'j' will be the last row and column respectively in square sub-matrix.
How to calculate S[i][j]:
We should note that if M[i][j] is '0' then S[i][j] will obviously be '0'. If M[i][j] is '1' then S[i][j] depends on earlier values.
If M[i][j] is '1' then it will contribute to the all 1s square sub-matrix ending at either M[i][j-1] or M[i-1][j] or M[i-1][j-1]. If we visualize the conditions then, we will see:
X. DP: O(m * n) 空间, dp[i][j] 代表以i,j为右下角的正方形边长
O(n)空间优化,注意 else 语句将 dp[j] 清0
Code from http://www.geeksforgeeks.org/maximum-size-sub-matrix-with-all-1s-in-a-binary-matrix/
Space Optimization:
https://leetcode.com/discuss/38520/java-o-n-2-time-o-n-space
http://blog.csdn.net/chibaoneliuliuni/article/details/46385175
因为你每次更新dp值的时候只需要知道当前行前一列的值, 前一行的当前值, 以及前一行的前一列的值,所以用两个一位数组分别记录当前行和前一行的值就可以了。
int[] dp = new int[matrix[0].length];
int maxLen = 0;
// int tmpPre = 0; 本来是想用一个变量来存储 top-left 的值, 其实可以用另一个二维数组来存上一排的信息, 这样两个一位数组就可以了, 也是一种空间的优化。
int[] pre = new int[matrix[0].length];
for(int i = 0; i < matrix[0].length; i++){
dp[i] = Character.getNumericValue(matrix[0][i]);
pre[i] = dp[i];
if(dp[i] > maxLen){
maxLen = dp[i];
}
}
for(int i = 1; i < matrix.length; i++){
for(int j = 0; j < matrix[0].length; j++){
if(j == 0){
dp[j] = Character.getNumericValue(matrix[i][j]);
if(dp[j] > maxLen){
maxLen = dp[j];
}
}else{
if(matrix[i][j] == '0'){
dp[j] = 0;
}else{
dp[j] = Math.min(Math.min(dp[j], dp[j - 1]), pre[j - 1]) + 1;
if(dp[j] > maxLen){
maxLen = dp[j];
}
}
}
}
// set curRow dp[] as pre[], so in the next row we still have the info of the cur row.
for(int k = 0; k < dp.length; k++){
pre[k] = dp[k];
}
}
return maxLen * maxLen;
}
其实每次对新的一行扫描时, 把dp【j】用一个变量tmp存起来, 然后到当前行下一列的时候这个tmp就是dp【i - 1】【j - 1】了, 因为在整个一行的for loop 进行之前, dp【j】中存的值都是上一行的值,
public int maximalSquare(char[][] matrix) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
return 0;
}
int[] dp = new int[matrix[0].length];
int maxLen = 0;
int lastPre = 0;
for(int i = 0; i < matrix[0].length; i++){
dp[i] = Character.getNumericValue(matrix[0][i]);
if(dp[i] > maxLen){
maxLen = dp[i];
}
}
for(int i = 1; i < matrix.length; i++){
for(int j = 0; j < matrix[0].length; j++){
int tmp = dp[j];
if(j == 0){
dp[j] = Character.getNumericValue(matrix[i][j]);
if(dp[j] > maxLen){
maxLen = dp[j];
}
}else{
if(matrix[i][j] == '0'){
dp[j] = 0;
}else{
dp[j] = Math.min(Math.min(dp[j], dp[j - 1]), lastPre) + 1;
if(dp[j] > maxLen){
maxLen = dp[j];
}
}
}
lastPre = tmp;
}
}
return maxLen * maxLen;
}
http://zwzbill8.blogspot.com/2015/06/leetcode-maximal-square.html
Code in Java: O(mn) time complexity, O(n) space complexity. This can be easily improved to O(min{m, n}) by comparing m and n first, and then deciding the order of the two loops.
Using max rectangle in Histogram
http://likesky3.iteye.com/blog/2216826
此题是Maximal Rectangle的变形题,思路仍然是求解各行为底的直方图中的最大正方形面积然后取最大值。求解某一行为底的直方图中的最大正方形面积,要求全1区域的宽度 >= 高度。
https://codesolutiony.wordpress.com/2015/06/03/leetcode-maximal-square/
Brute Force: O(N^3)
http://www.cnblogs.com/easonliu/p/4548769.html
确定了左顶点后,再往下扫的时候,正方形的竖边长度就确定了,只需要找到横边即可,这时候我们使用直方图的原理,从其累加值能反映出上面的值是否全为1
http://www.geeksforgeeks.org/maximum-size-sub-matrix-with-all-1s-in-a-binary-matrix/
Base Cases:
http://blog.csdn.net/u013027996/article/details/46380233
Leetcode: Maximal Rectangle:
http://massivealgorithms.blogspot.com/2015/06/my-leetcode-maximal-rectangle-java.html
http://siddontang.gitbooks.io/leetcode-solution/content/array/largest_rectangle_in_histogram.html
Maximum size square sub-matrix with all 1s - Dynamic Programming Questions
http://www.geeksforgeeks.org/finding-the-maximum-square-sub-matrix-with-all-equal-elements/
http://blog.csdn.net/u014688145/article/details/70820874
public int maximalSquare(char[][] matrix) {
if (matrix.length == 0 || matrix[0].length == 0) return 0;
int n = matrix.length, m = matrix[0].length;
int[][] dp = new int[n+1][m+1];
int max = 0;
for(int i = 0; i < n; i++){
for (int j = 0; j < m; j++){
if (matrix[i][j] == '1'){
dp[i+1][j+1] = Math.min(dp[i][j+1], Math.min(dp[i+1][j], dp[i][j])) + 1;
max = Math.max(max, dp[i+1][j+1]);
}
}
}
return max * max;
}
https://cp-algorithms.com/dynamic_programming/zero_matrix.html
Read full article from Maximum size square sub-matrix with all 1s | PROGRAMMING INTERVIEWS
http://www.geeksforgeeks.org/maximum-size-sub-matrix-with-all-1s-in-a-binary-matrix/
Given a matrix consisting only 0s and 1s, find the maximum size square sub-matrix with all 1s.
Time Complexity: O(m*n)
Auxiliary Space: O(m*n)
The idea of the algorithm is to construct an auxiliary size matrix S[][] in which each entry S[i][j] represents size of the square sub-matrix with all 1s including M[i][j] where M[i][j] is the rightmost and bottommost entry in sub-matrix.
1) Construct a sum matrix S[R][C] for the given M[R][C].
a) Copy first row and first columns as it is from M[][] to S[][]
b) For other entries, use following expressions to construct S[][]
If M[i][j] is 1 then
S[i][j] = min(S[i][j-1], S[i-1][j], S[i-1][j-1]) + 1
Else /*If M[i][j] is 0*/
S[i][j] = 0
2) Find the maximum entry in S[R][C]
3) Using the value and coordinates of maximum entry in S[i], print
sub-matrix of M[][]
https://leetcode.com/articles/maximal-square/
We initialize another matrix (dp) with the same dimensions as the original one initialized with all 0’s.
dp(i,j) represents the side length of the maximum square whose bottom right corner is the cell with index (i,j) in the original matrix.
Starting from index (0,0), for every 1 found in the original matrix, we update the value of the current element as
We also remember the size of the largest square found so far. In this way, we traverse the original matrix once and find out the required maximum size. This gives the side length of the square (say ). The required result is the area
Approach #3 (Better Dynamic Programming) [Accepted]
In the previous approach for calculating dp of row we are using only the previous element and the row. Therefore, we don't need 2D dp matrix as 1D dp array will be sufficient for this.
Initially the dp array contains all 0's. As we scan the elements of the original matrix across a row, we keep on updating the dp array as per the equation , where prev refers to the old . For every row, we repeat the same process and update in the same dp array.
public int maximalSquare(char[][] matrix) { int rows = matrix.length, cols = rows > 0 ? matrix[0].length : 0; int[] dp = new int[cols + 1]; int maxsqlen = 0, prev = 0; for (int i = 1; i <= rows; i++) { for (int j = 1; j <= cols; j++) { int temp = dp[j]; if (matrix[i - 1][j - 1] == '1') { dp[j] = Math.min(Math.min(dp[j - 1], prev), dp[j]) + 1; maxsqlen = Math.max(maxsqlen, dp[j]); } else { dp[j] = 0; } prev = temp; } } return maxsqlen * maxsqlen; }
http://www.programcreek.com/2014/06/leetcode-maximal-square-java/
This problem can be solved by dynamic programming. The changing condition is:
t[i][j] = min(t[i][j-1], t[i-1][j], t[i-1][j-1]) + 1. It means the square formed before this point.
t[i][j] = min(t[i][j-1], t[i-1][j], t[i-1][j-1]) + 1. It means the square formed before this point.
We will use a auxiliary matrix S[][] of same size for memoization. S[i][j] represents size of the square sub-matrix with all 1s including M[i][j]. 'i' and 'j' will be the last row and column respectively in square sub-matrix.
How to calculate S[i][j]:
We should note that if M[i][j] is '0' then S[i][j] will obviously be '0'. If M[i][j] is '1' then S[i][j] depends on earlier values.
If M[i][j] is '1' then it will contribute to the all 1s square sub-matrix ending at either M[i][j-1] or M[i-1][j] or M[i-1][j-1]. If we visualize the conditions then, we will see:
S[i][j] = min(S[i][j-1], S[i-1][j], S[i-1][j-1]) + 1http://shibaili.blogspot.com/2015/06/day-111-contains-duplicate-ii.html
X. DP: O(m * n) 空间, dp[i][j] 代表以i,j为右下角的正方形边长
int
maximalSquare(vector<vector<
char
>>& matrix) {
int
m = matrix.size();
if
(m == 0)
return
0;
int
n = matrix[0].size();
vector<vector<
int
> > dp(m,vector<
int
>(n,0));
int
maxSquare = 0;
for
(
int
i = 0; i < m; i++) {
if
(matrix[i][0] ==
'1'
) {
dp[i][0] = 1;
maxSquare = 1;
}
}
for
(
int
i = 0; i < n; i++) {
if
(matrix[0][i] ==
'1'
) {
dp[0][i] = 1;
maxSquare = 1;
}
}
for
(
int
i = 1; i < m; i++) {
for
(
int
j = 1; j < n; j++) {
if
(matrix[i][j] ==
'1'
) {
dp[i][j] = 1 + min(dp[i - 1][j - 1],min(dp[i - 1][j],dp[i][j - 1]));
maxSquare = max(maxSquare,dp[i][j]);
}
}
}
return
maxSquare * maxSquare;
}
int
maximalSquare(vector<vector<
char
>>& matrix) {
int
m = matrix.size();
if
(m == 0)
return
0;
int
n = matrix[0].size();
vector<
int
> dp(n + 1, 0);
int
maxSquare = 0, pre = 0;
for
(
int
i = 0; i < m; i++) {
for
(
int
j = 1; j < n + 1; j++) {
int
temp = dp[j];
if
(matrix[i][j - 1] ==
'1'
) {
dp[j] = 1 + min(dp[j - 1],min(pre,dp[j]));
maxSquare = max(maxSquare,dp[j]);
}
else
{
dp[j] = 0;
}
pre = temp;
}
}
return
maxSquare * maxSquare;
}
void
printMaxSubSquare(
bool
M[R][C])
{
int
i,j;
int
S[R][C];
int
max_of_s, max_i, max_j;
/* Set first column of S[][]*/
for
(i = 0; i < R; i++)
S[i][0] = M[i][0];
/* Set first row of S[][]*/
for
(j = 0; j < C; j++)
S[0][j] = M[0][j];
/* Construct other entries of S[][]*/
for
(i = 1; i < R; i++)
{
for
(j = 1; j < C; j++)
{
if
(M[i][j] == 1)
S[i][j] = min(S[i][j-1], S[i-1][j], S[i-1][j-1]) + 1;
else
S[i][j] = 0;
}
}
/* Find the maximum entry, and indexes of maximum entry
in S[][] */
max_of_s = S[0][0]; max_i = 0; max_j = 0;
for
(i = 0; i < R; i++)
{
for
(j = 0; j < C; j++)
{
if
(max_of_s < S[i][j])
{
max_of_s = S[i][j];
max_i = i;
max_j = j;
}
}
}
printf
(
"\n Maximum size sub-matrix is: \n"
);
for
(i = max_i; i > max_i - max_of_s; i--)
{
for
(j = max_j; j > max_j - max_of_s; j--)
{
printf
(
"%d "
, M[i][j]);
}
printf
(
"\n"
);
}
}
https://leetcode.com/discuss/38520/java-o-n-2-time-o-n-space
public int maximalSquare(char[][] matrix) {
if(matrix.length==0) return 0;
int cols = matrix[0].length;
int[] m = new int[cols];
int max = 0;
for(int i = 0; i < cols; i++){
m[i] = matrix[0][i] - '0';
max = Math.max(m[i], max);
}
for(int i = 1; i < matrix.length; i++){
m[cols-1] = matrix[i][cols-1]-'0';
max = Math.max(m[cols-1], max);
for(int j = matrix[0].length-2; j >= 0; j--){
if(matrix[i][j]=='0'){
m[j] = 0;
} else if(m[j] != m[j+1] || matrix[i-m[j]][j+m[j+1]]=='1') {
m[j] = Math.min(m[j], m[j+1]) + 1;
}
max = Math.max(m[j], max);
}
}
return max*max;
}
因为你每次更新dp值的时候只需要知道当前行前一列的值, 前一行的当前值, 以及前一行的前一列的值,所以用两个一位数组分别记录当前行和前一行的值就可以了。
int[] dp = new int[matrix[0].length];
int maxLen = 0;
// int tmpPre = 0; 本来是想用一个变量来存储 top-left 的值, 其实可以用另一个二维数组来存上一排的信息, 这样两个一位数组就可以了, 也是一种空间的优化。
int[] pre = new int[matrix[0].length];
for(int i = 0; i < matrix[0].length; i++){
dp[i] = Character.getNumericValue(matrix[0][i]);
pre[i] = dp[i];
if(dp[i] > maxLen){
maxLen = dp[i];
}
}
for(int i = 1; i < matrix.length; i++){
for(int j = 0; j < matrix[0].length; j++){
if(j == 0){
dp[j] = Character.getNumericValue(matrix[i][j]);
if(dp[j] > maxLen){
maxLen = dp[j];
}
}else{
if(matrix[i][j] == '0'){
dp[j] = 0;
}else{
dp[j] = Math.min(Math.min(dp[j], dp[j - 1]), pre[j - 1]) + 1;
if(dp[j] > maxLen){
maxLen = dp[j];
}
}
}
}
// set curRow dp[] as pre[], so in the next row we still have the info of the cur row.
for(int k = 0; k < dp.length; k++){
pre[k] = dp[k];
}
}
return maxLen * maxLen;
}
其实每次对新的一行扫描时, 把dp【j】用一个变量tmp存起来, 然后到当前行下一列的时候这个tmp就是dp【i - 1】【j - 1】了, 因为在整个一行的for loop 进行之前, dp【j】中存的值都是上一行的值,
public int maximalSquare(char[][] matrix) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
return 0;
}
int[] dp = new int[matrix[0].length];
int maxLen = 0;
int lastPre = 0;
for(int i = 0; i < matrix[0].length; i++){
dp[i] = Character.getNumericValue(matrix[0][i]);
if(dp[i] > maxLen){
maxLen = dp[i];
}
}
for(int i = 1; i < matrix.length; i++){
for(int j = 0; j < matrix[0].length; j++){
int tmp = dp[j];
if(j == 0){
dp[j] = Character.getNumericValue(matrix[i][j]);
if(dp[j] > maxLen){
maxLen = dp[j];
}
}else{
if(matrix[i][j] == '0'){
dp[j] = 0;
}else{
dp[j] = Math.min(Math.min(dp[j], dp[j - 1]), lastPre) + 1;
if(dp[j] > maxLen){
maxLen = dp[j];
}
}
}
lastPre = tmp;
}
}
return maxLen * maxLen;
}
http://zwzbill8.blogspot.com/2015/06/leetcode-maximal-square.html
Code in Java: O(mn) time complexity, O(n) space complexity. This can be easily improved to O(min{m, n}) by comparing m and n first, and then deciding the order of the two loops.
public int maximalSquare(char[][] matrix) { int m = matrix.length; if (m == 0) { return 0; } int n = matrix[0].length; int max_so_far = 0; int[] max_ending_here = new int[n]; Arrays.fill(max_ending_here, 0); int upper_left_max_ending_here = 0; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (matrix[i][j] == '0') { upper_left_max_ending_here = max_ending_here[j]; max_ending_here[j] = 0; continue; } //Now matrix[i][j] == '1' if (i == 0 || j == 0) { upper_left_max_ending_here = max_ending_here[j]; max_ending_here[j] = 1; } else { int tmp = max_ending_here[j]; max_ending_here[j] = Math.min( Math.min( max_ending_here[j - 1], max_ending_here[j] ), upper_left_max_ending_here ) + 1; upper_left_max_ending_here = tmp; } if (max_so_far < max_ending_here[j]) { max_so_far = max_ending_here[j]; } } } return max_so_far * max_so_far; }
Using max rectangle in Histogram
http://likesky3.iteye.com/blog/2216826
此题是Maximal Rectangle的变形题,思路仍然是求解各行为底的直方图中的最大正方形面积然后取最大值。求解某一行为底的直方图中的最大正方形面积,要求全1区域的宽度 >= 高度。
- public int maximalSquare(char[][] matrix) {
- if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
- return 0;
- int rows = matrix.length;
- int cols = matrix[0].length;
- int[] h = new int[cols + 1];
- int max = 0;
- for (int i = 0; i < rows; i++) {
- for (int j = 0; j < cols; j++) {
- if (matrix[i][j] == '1')
- h[j] += 1;
- else
- h[j] = 0;
- }
- max = Math.max(max, getLargestSquare(h));
- }
- return max;
- }
- private int getLargestSquare(int[] h) {
- LinkedList<Integer> stack = new LinkedList<Integer>();
- int max = 0;
- int i = 0;
- while (i < h.length) {
- if (stack.isEmpty() || h[i] >= h[stack.peek()]) {
- stack.push(i++);
- } else {
- int currH = h[stack.pop()];
- while (!stack.isEmpty() && h[stack.peek()] == currH)
- stack.pop();
- int width = stack.isEmpty() ? i : (i - stack.peek() - 1);
- if (width >= currH)
- max = Math.max(max, currH * currH);
- }
- }
- return max;
- }
https://codesolutiony.wordpress.com/2015/06/03/leetcode-maximal-square/
public int maximalSquare(char[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return 0;
}
int[] store = new int[matrix[0].length];
int res = 0;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
if (matrix[i][j] == '0') {
store[j] = 0;
} else {
store[j]++;
}
}
res = Math.max(res, getRes(store));
}
return res;
}
private int getRes(int[] store) {
Stack<Integer> stack = new Stack<Integer>();
int res = 0;
for (int i = 0; i < store.length; i++) {
while (!stack.isEmpty() && store[i] < store[stack.peek()]) {
int index = stack.pop();
int height = store[index];
int preIndex = stack.isEmpty() ? -1 : stack.peek();
int width = i - preIndex - 1;
res = Math.max(res, height < width ? height*height : width *width);
}
stack.push(i);
}
while (!stack.isEmpty()) {
int index = stack.pop();
int height = store[index];
int preIndex = stack.isEmpty() ? -1 : stack.peek();
int width = store.length - preIndex - 1;
res = Math.max(res, height < width ? height*height : width *width);
}
return res;
}
Brute Force: O(N^3)
http://www.cnblogs.com/easonliu/p/4548769.html
确定了左顶点后,再往下扫的时候,正方形的竖边长度就确定了,只需要找到横边即可,这时候我们使用直方图的原理,从其累加值能反映出上面的值是否全为1
3 int getArea(vector<int> &array, int k) { 4 if (array.size() < k) return 0; 5 int cnt = 0; 6 for (int i = 0; i < array.size(); ++i) { 7 if (array[i] != k) cnt = 0; 8 else ++cnt; 9 if (cnt == k) return k * k; 10 } 11 return 0; 12 } 13 int maximalSquare(vector<vector<char>>& matrix) { 14 vector<int> array; 15 int res = 0; 16 for (int i = 0; i < matrix.size(); ++i) { 17 array.assign(matrix[0].size(), 0); 18 for (int j = i; j < matrix.size(); ++j) { 19 for (int k = 0; k < matrix[0].size(); ++k) if (matrix[j][k] == '1') ++array[k]; 20 res = max(res, getArea(array, j-i+1)); 21 } 22 } 23 return res; 24 }http://algorithms.tutorialhorizon.com/dynamic-programming-maximum-size-square-sub-matrix-with-all-1s/
http://www.geeksforgeeks.org/maximum-size-sub-matrix-with-all-1s-in-a-binary-matrix/
- Create an auxiliary array of the same size as given input array. We will fill the auxiliary array with Maximum size square sub-matrix with all 1’s possible with respect to the particular cell.
- Once the auxiliary is fill, scan it and find out the maximum entry in it, this will the size of Maximum size square sub-matrix with all 1’s in the given matrix.
How to fill the auxiliary matrix??
- Copy the first row and first column from the given array to auxiliary array. (Read the base cases described earlier).
- For filling rest of cells, check if particular cell’s value is 0 in given array, if yes then put 0 against to that cell in auxiliary array.
- check if particular cell’s value is 1 in given array, if yes then put Minimum (value in the left cell, top cell and left-top diagonal cell) + 1 in auxiliary cell.
Recursive Equation:
Base Cases:
sub[i][0] = arrA[i][0] i = 0 to row Count // copy the first column
sub[0][i] = arrA[0][i] i = 0 to column Count // copy the first row
for rest of the cells
sub[i][j] = 0 if arrA[i][j]=0 = Min(arrA[i-1][j], arrA[i][j-1], arrA[i-1][j-1] )
At the End, scan the sub[][] and find out the maximum entry in it.
Also check http://n00tc0d3r.blogspot.com/2013/04/maximum-rectangle.htmlsub[i][j] = 0 if arrA[i][j]=0 = Min(arrA[i-1][j], arrA[i][j-1], arrA[i-1][j-1] )
At the End, scan the sub[][] and find out the maximum entry in it.
http://blog.csdn.net/u013027996/article/details/46380233
Leetcode: Maximal Rectangle:
http://massivealgorithms.blogspot.com/2015/06/my-leetcode-maximal-rectangle-java.html
http://siddontang.gitbooks.io/leetcode-solution/content/array/largest_rectangle_in_histogram.html
Maximum size square sub-matrix with all 1s - Dynamic Programming Questions
http://www.geeksforgeeks.org/finding-the-maximum-square-sub-matrix-with-all-equal-elements/
Given a N x N matrix, determine the maximum K such that K x K is a submatrix with all equal elements i.e., all the elements in this submatrix must be same.
Input : a[][] = {{9, 9, 9, 8}, {9, 9, 9, 6}, {9, 9, 9, 3}, {2, 2, 2, 2} Output : 3 Explanation : A 3x3 matrix is formed from index A0,0 to A2,2
We can easily find all the square submatrices in O(n3) time and check whether each submatrix contains equal elements or not in O(n2) time Which makes the total running time of the algorithm as O(n5).
int
largestKSubmatrix(
int
a[][Col])
{
int
dp[Row][Col];
memset
(dp,
sizeof
(dp), 0);
int
result = 0;
for
(
int
i = 0 ; i < Row ; i++)
{
for
(
int
j = 0 ; j < Col ; j++)
{
// If elements is at top row or first
// column, it wont form a square
// matrix's bottom-right
if
(i == 0 || j == 0)
dp[i][j] = 1;
else
{
// Check if adjacent elements are equal
if
(a[i][j] == a[i-1][j] &&
a[i][j] == a[i][j-1] &&
a[i][j] == a[i-1][j-1] )
dp[i][j] = min(min(dp[i-1][j], dp[i][j-1]),
dp[i-1][j-1] ) + 1;
// If not equal, then it will form a 1x1
// submatrix
else
dp[i][j] = 1;
}
// Update result at each (i,j)
result = max(result, dp[i][j]);
}
}
return
result;
}
http://blog.csdn.net/u014688145/article/details/70820874
呵呵,如果就着前面的思路,那么就完蛋了,反正我是又做不出来了。这道题的思路比较奇葩,是一道较难的dp题。咋说呢,我其实还没掌握它的核心思想。用的是正方形生成性质,很难理解它为啥是正确的。
状态转移方程:
dp[i+1][j+1] = Math.min(dp[i][j+1], Math.min(dp[i+1][j], dp[i][j])) + 1;
其中
i和j
,分别表示在当前坐标(i,j)
能够生成最大矩形的长。
所以说新的正方形,一定是那三个状态的最小值,否则不可能构成一个更大的正方形,自己笔画下
这道题给了我dp的一个新思路,不一定dp要记录每一步的最优解,即dp到最后不一定就是本题的答案,相反,我们可以在dp更新的时候,时刻更新max,那么求解它的思路和想法就广了很多。
https://cp-algorithms.com/dynamic_programming/zero_matrix.html
Read full article from Maximum size square sub-matrix with all 1s | PROGRAMMING INTERVIEWS