Skip to content

Commit 13e50c9

Browse files
authored
Create 01 - Recursive Approach (casued TLE).cpp
1 parent 00d7eee commit 13e50c9

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// User function Template for C++
2+
class Solution {
3+
public:
4+
// Recursive function to find the size of the largest square ending at (i, j)
5+
int solve(vector<vector<int>>& mat, int i, int j, int &maxi) {
6+
// Base condition: If out of bounds, return 0
7+
if (i >= mat.size() || j >= mat[0].size()) return 0;
8+
9+
// Recursive calls to calculate the size of squares in three directions:
10+
int right = solve(mat, i, j + 1, maxi); // Square ending to the right
11+
int diagnol = solve(mat, i + 1, j + 1, maxi); // Square ending diagonally
12+
int down = solve(mat, i + 1, j, maxi); // Square ending below
13+
14+
// If the current cell contains 1
15+
if (mat[i][j] == 1) {
16+
// Calculate the size of the square ending at (i, j)
17+
int ans = 1 + min(right, min(diagnol, down));
18+
19+
// Update the maximum square size
20+
maxi = max(maxi, ans);
21+
return ans; // Return the size of the square at (i, j)
22+
}
23+
24+
// If the current cell contains 0, it cannot form a square
25+
return 0;
26+
}
27+
28+
// Main function to find the largest square submatrix with all 1s
29+
int maxSquare(vector<vector<int>>& mat) {
30+
int maxi = 0; // Variable to store the maximum square size
31+
solve(mat, 0, 0, maxi); // Start solving from the top-left corner
32+
return maxi; // Return the maximum square size
33+
}
34+
};

0 commit comments

Comments
 (0)