Skip to content

Commit 402cae7

Browse files
Added solution
1 parent 7a9ef36 commit 402cae7

File tree

1 file changed

+72
-4
lines changed

1 file changed

+72
-4
lines changed

maximal_rectangle.cpp

Lines changed: 72 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,93 @@
11
class Solution {
22
public:
3+
/*
34
int dfs(vector<vector<char>>& matrix, int i, int j){
45
if(i < 0 or j < 0 or i >= matrix.size() or j >= matrix[i].size() or matrix[i][j] == '0')
56
return 0;
67
else{
78
matrix[i][j] = '0';
89
return 1 + dfs(matrix, i-1, j) + dfs(matrix, i+1, j) + dfs(matrix, i, j + 1) + dfs(matrix, i, j - 1);
910
}
11+
}*/
12+
13+
int largestRectangleArea(vector<int>& heights) {
14+
15+
/*
16+
if(heights.size() == 0) return 0;
17+
18+
stack<int> st;
19+
int max_rect_area = INT_MIN;
20+
int index, curr_area, i;
21+
22+
for(i=0; i<=heights.size(); i++){
23+
int cheight = i == heights.size() ? 0 : heights[i];
24+
if(st.empty() || cheight >= heights[st.top()]){
25+
st.push(i++);
26+
}
27+
else{
28+
index = st.top();
29+
st.pop();
30+
*/
31+
/*
32+
height[index] = max_rect_seen_so_far
33+
if stack is empty..
34+
there is no earlier start that is present
35+
this means... the current rect is the only start and end..
36+
hence, curr_area = height[index] * i;
37+
38+
if stack is not empty..
39+
there is earlier start that is present
40+
this means... the current rect has the end..
41+
hence, curr_area = height[index] * (i - s.top() - 1)
42+
*/
43+
/*
44+
int breadth = st.empty() ? i : i - st.top() - 1;
45+
max_rect_area = max(max_rect_area, heights[index] * breadth);
46+
}
47+
}
48+
49+
/*
50+
while(!st.empty()){
51+
index = st.top();
52+
st.pop();
53+
curr_area = heights[index] * (st.empty() ? i : i - st.top() - 1);
54+
max_rect_area = max(curr_area, max_rect_area);
55+
}*/
56+
//return max_rect_area;
57+
int ans = 0;
58+
int len = heights.size();
59+
if(len == 0){
60+
return 0;
61+
}
62+
stack<int> st;
63+
for(int i = 0; i <= len;){
64+
int h = (i == len ? 0 : heights[i]);
65+
if(st.empty() || heights[st.top()] <= h){
66+
st.push(i++);
67+
}else{
68+
int tmp = st.top();
69+
st.pop();
70+
int l = (st.empty() ? i : i - st.top() - 1);
71+
ans = max(ans, l * heights[tmp]);
72+
}
73+
}
74+
return ans;
1075
}
1176

1277
int maximalRectangle(vector<vector<char>>& matrix) {
1378
if(matrix.size() == 0) return 0;
79+
1480
auto curr_area = 0, max_area = INT_MIN;
81+
vector<int> heights(matrix[0].size());
1582

1683
for(auto i = 0; i < matrix.size(); i++){
1784
for(auto j = 0; j < matrix[i].size(); j++){
18-
if(matrix[i][j] == '1'){
19-
curr_area = dfs(matrix, i, j);
20-
max_area = max(max_area, curr_area);
21-
}
85+
if(matrix[i][j] == '0')
86+
heights[j] = 0 ;
87+
else
88+
heights[j]++;
2289
}
90+
max_area = max(max_area, largestRectangleArea(heights));
2391
}
2492
return max_area;
2593
}

0 commit comments

Comments
 (0)