Skip to content

Commit 36677e5

Browse files
authored
Create LargestSquareSubMatrixOf1.java
1 parent e583f35 commit 36677e5

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/*
2+
https://www.techiedelight.com/find-size-largest-square-sub-matrix-1s-present-given-binary-matrix/
3+
4+
*/
5+
6+
//Bottom up DP
7+
8+
public int maxSizeOfSquareSubMatrix(int A[][]){
9+
int n = A.length;
10+
int m = A[0].length;
11+
12+
//dp[i][j] indicates the side-length of the largest square sub-matrix formed when (i,j) is the bottom-right corner of that sub-matrix
13+
int dp[][] = new int[n][m];
14+
15+
int maxSize = 0;
16+
17+
for(int i=0;i<n;i++){
18+
for(int j=0;j<m;j++){
19+
20+
dp[i][j] = A[i][j];
21+
22+
//if we are not in the first row or column and the current element is 1, then check for sub-matrix
23+
if(i>0 && j>0 && A[i][j]==1){
24+
//dp[i-1][j] --> Top cell
25+
//dp[i][j-1] --> left cell
26+
//dp[i-1][j-1] --> top left cell
27+
//we chose the minimum value because it is the LIMITING VALUE and we can not have a square sub-matrix
28+
//of length greater than this minimum value
29+
dp[i][j] = Math.min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1;
30+
}
31+
32+
maxSize = Math.max(maxSize, dp[i][j]);
33+
}
34+
}
35+
36+
return maxSize;
37+
38+
}
39+
40+
/*
41+
Time and Space Complexity - O(n*m)
42+
*/

0 commit comments

Comments
 (0)