Skip to content

Commit 816c73d

Browse files
authored
Create 04 - Space Optimized - 1 | DP | Approach.cpp
1 parent db6b166 commit 816c73d

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// User function Template for C++
2+
class Solution {
3+
public:
4+
// Function to compute the largest square submatrix with all 1s using space optimization
5+
int solve(vector<vector<int>>& mat, int& maxi) {
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+
// Two 1D vectors to store the current and next rows of the DP table
14+
vector<int> curr(m + 1, 0); // Current row
15+
vector<int> next(m + 1, 0); // Next row
16+
17+
// Iterate through the matrix in reverse (bottom to top, right to left)
18+
for (int i = n - 1; i >= 0; i--) {
19+
for (int j = m - 1; j >= 0; j--) {
20+
// Fetch values from the next row and the current row (for right, diagonal, and down)
21+
int right = curr[j + 1]; // Cell to the right
22+
int diagnol = next[j + 1]; // Diagonal cell
23+
int down = next[j]; // Cell below
24+
25+
// If the current cell contains 1, calculate the size of the square ending here
26+
if (mat[i][j] == 1) {
27+
curr[j] = 1 + min({right, diagnol, down}); // Add 1 to the smallest adjacent square
28+
maxi = max(maxi, curr[j]); // Update the maximum square size
29+
} else {
30+
curr[j] = 0; // If the cell contains 0, it cannot form a square
31+
}
32+
}
33+
34+
// Update the `next` row to the current row for the next iteration
35+
next = curr;
36+
}
37+
38+
return next[0]; // This value is not used but returned for compatibility
39+
}
40+
41+
// Main function to find the size of the largest square submatrix with all 1s
42+
int maxSquare(vector<vector<int>>& mat) {
43+
int maxi = 0; // Variable to store the maximum square size
44+
solve(mat, maxi); // Compute the largest square using the solve function
45+
return maxi; // Return the maximum square size
46+
}
47+
};

0 commit comments

Comments
 (0)