Skip to content

Instantly share code, notes, and snippets.

@pdu
Created January 17, 2013 15:25
Show Gist options
  • Select an option

  • Save pdu/4556704 to your computer and use it in GitHub Desktop.

Select an option

Save pdu/4556704 to your computer and use it in GitHub Desktop.
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area. http://leetcode.com/onlinejudge#question_85
class Solution {
public:
int maximalRectangle(vector<vector<char> > &matrix) {
int n = matrix.size();
if (0 == n)
return 0;
int m = matrix[0].size();
if (0 == m)
return 0;
int **f;
f = new int*[n];
for (int i = 0; i < n; ++i)
f[i] = new int[m];
for (int i = 0; i < n; ++i)
for (int j = 0; j < m; ++j)
f[i][j] = matrix[i][j] - '0' + (j > 0 ? f[i][j - 1] : 0);
int sz = 0;
int ret = 0;
for (int k = 0; k < m; ++k) {
sz = (m - k) * n;
if (sz <= ret)
break;
for (int t = m - 1; t >= k; --t) {
sz = (t - k + 1) * n;
if (sz <= ret)
break;
int beg = -1;
int end = -1;
for (int i = 0; i < n; ++i)
if (f[i][t] - (k > 0 ? f[i][k - 1] : 0) == t - k + 1) {
if (beg == -1)
beg = i;
end = i;
}
else {
if (beg != -1)
ret = max(ret, (t - k + 1) * (end - beg + 1));
beg = -1;
}
if (beg != -1)
ret = max(ret, (t - k + 1) * (end - beg + 1));
}
}
for (int i = 0; i < n; ++i)
delete[] f[i];
delete[] f;
return ret;
}
};
@Mukesh1412
Copy link
Copy Markdown

can you provide explanation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment