Skip to content

Commit ecab1eb

Browse files
authored
Create 05 - Space Optimized - 2 | DP | Approach.cpp
1 parent 816c73d commit ecab1eb

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// User function Template for C++
2+
class Solution {
3+
public:
4+
// Function to compute the largest square submatrix with all 1s using in-place modification
5+
int solve(vector<vector<int>>& mat) {
6+
// Edge case: If the matrix is empty, return 0
7+
if (mat.empty()) return 0;
8+
9+
// Dimensions of the matrix
10+
int n = mat.size();
11+
int m = mat[0].size();
12+
13+
// Variable to store the size of the largest square
14+
int maxi = 0;
15+
16+
// Traverse the matrix from bottom-right to top-left
17+
for (int i = n - 1; i >= 0; i--) {
18+
for (int j = m - 1; j >= 0; j--) {
19+
// If the cell is in the last row or last column, no need to modify its value
20+
if (i == n - 1 || j == m - 1) {
21+
maxi = max(maxi, mat[i][j]); // Update `maxi` if the cell contains `1`
22+
} else if (mat[i][j] == 1) {
23+
// If the current cell contains `1`, calculate the size of the square
24+
mat[i][j] = 1 + min({mat[i + 1][j], mat[i][j + 1], mat[i + 1][j + 1]});
25+
maxi = max(maxi, mat[i][j]); // Update `maxi` if the square size increases
26+
}
27+
}
28+
}
29+
30+
return maxi; // Return the size of the largest square
31+
}
32+
33+
// Main function to find the size of the largest square submatrix with all 1s
34+
int maxSquare(vector<vector<int>>& mat) {
35+
return solve(mat); // Call the solve function
36+
}
37+
};

0 commit comments

Comments
 (0)