Skip to content

Commit db6b166

Browse files
authored
Create 03 - Bottom-Up | DP | Approach.cpp
1 parent f31a307 commit db6b166

File tree

1 file changed

+43
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)